Post-lesson tasks: шаги и закрытие с причиной в БД
- Добавлены таблицы post_lesson_task_states и post_lesson_task_closures (init.sql, migration.sql, ensurePostLessonTaskTables при старте) - Новые API: POST /api/post-lesson-tasks/step, POST /close, DELETE /close - Состояние шагов (is_done, reason) и факт закрытия задачи (close_reason) хранятся в БД вместо localStorage - При ручном закрытии шага или задачи запрашивается причина в модалке - Синхронизация между postlesson.html и дашбордом через БД - lib/post-lesson-tasks.js — бизнес-логика post-lesson задач
This commit is contained in:
+150
-71
@@ -1,22 +1,8 @@
|
||||
const POST_TASK_DISMISSED_KEY = 'dashboard.postLessonTasks.dismissed';
|
||||
const POST_TASK_STEPS_KEY = 'dashboard.postLessonTasks.stepOverrides';
|
||||
function getPostTaskDismissed() {
|
||||
try { return new Set(JSON.parse(localStorage.getItem(POST_TASK_DISMISSED_KEY) || '[]')); } catch (e) { return new Set(); }
|
||||
}
|
||||
function savePostTaskDismissed(set) {
|
||||
try { localStorage.setItem(POST_TASK_DISMISSED_KEY, JSON.stringify([...set])); } catch (e) {}
|
||||
}
|
||||
function getPostTaskStepOverrides() {
|
||||
try { return JSON.parse(localStorage.getItem(POST_TASK_STEPS_KEY) || '{}') || {}; } catch (e) { return {}; }
|
||||
}
|
||||
function savePostTaskStepOverrides(obj) {
|
||||
try { localStorage.setItem(POST_TASK_STEPS_KEY, JSON.stringify(obj || {})); } catch (e) {}
|
||||
}
|
||||
|
||||
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,'>').replace(/"/g,'"'); }
|
||||
|
||||
@@ -35,19 +21,14 @@ async function loadPostLessonTasks() {
|
||||
function filteredTasks() {
|
||||
const q = (document.getElementById('plSearch').value || '').trim().toLowerCase();
|
||||
const status = document.getElementById('plStatus').value;
|
||||
const showDismissed = document.getElementById('plShowDismissed').checked;
|
||||
const dismissed = getPostTaskDismissed();
|
||||
const overrides = getPostTaskStepOverrides();
|
||||
const showClosed = document.getElementById('plShowDismissed').checked;
|
||||
return allPostTasks.filter(t => {
|
||||
if (q && !String(t.group_name || '').toLowerCase().includes(q)) return false;
|
||||
const taskOverride = overrides[t.key] || {};
|
||||
const steps = t.steps.map(s => ({ ...s, done: s.done || !!taskOverride[s.key] }));
|
||||
const allDone = steps.every(s => s.done);
|
||||
const isDismissed = dismissed.has(t.key);
|
||||
if (!showDismissed && isDismissed) return false;
|
||||
if (status === 'pending' && (allDone || isDismissed)) return false;
|
||||
if (status === 'completed' && !allDone) return false;
|
||||
if (status === 'overdue' && !(t.overdue && !allDone)) 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;
|
||||
});
|
||||
}
|
||||
@@ -77,8 +58,6 @@ function renderPostLessonTasks() {
|
||||
const el = document.getElementById('plList');
|
||||
const summary = document.getElementById('plSummary');
|
||||
if (!el) return;
|
||||
const dismissed = getPostTaskDismissed();
|
||||
const overrides = getPostTaskStepOverrides();
|
||||
const visible = filteredTasks();
|
||||
currentPostTasks = visible;
|
||||
if (!visible.length) {
|
||||
@@ -87,14 +66,10 @@ function renderPostLessonTasks() {
|
||||
renderPager(0);
|
||||
return;
|
||||
}
|
||||
const pendingCount = visible.filter(t => {
|
||||
const to = overrides[t.key] || {};
|
||||
const steps = t.steps.map(s => ({ ...s, done: s.done || !!to[s.key] }));
|
||||
return !steps.every(s => s.done);
|
||||
}).length;
|
||||
const pendingCount = visible.filter(t => !t.all_done && !t.closed).length;
|
||||
const overdueCount = visible.filter(t => t.overdue && !t.all_done).length;
|
||||
const dismissedCount = allPostTasks.filter(t => dismissed.has(t.key)).length;
|
||||
if (summary) summary.textContent = `Всего: ${visible.length} · невыполненных: ${pendingCount} · просроченных: ${overdueCount} · закрытых: ${dismissedCount}`;
|
||||
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));
|
||||
@@ -104,21 +79,20 @@ function renderPostLessonTasks() {
|
||||
const pageItems = visible.slice(start, start + pageSize);
|
||||
|
||||
el.innerHTML = pageItems.map(t => {
|
||||
const taskOverride = overrides[t.key] || {};
|
||||
const steps2 = t.steps.map(s => ({ ...s, done: s.done || !!taskOverride[s.key], manual: !s.done && !!taskOverride[s.key] }));
|
||||
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 isDismissed = dismissed.has(t.key);
|
||||
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 (isDismissed) { badgeCls = 'dismissed'; badgeText = 'Закрыта'; barColor = '#94a3b8'; }
|
||||
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 `
|
||||
<div class="post-task ${allDone ? 'all-done' : ''} ${isOverdue ? 'overdue' : ''} ${isDismissed ? 'dismissed' : ''}" data-task-key="${esc(t.key)}" data-task-link="${esc(link)}">
|
||||
<div class="post-task ${allDone ? 'all-done' : ''} ${isOverdue ? 'overdue' : ''} ${isClosed ? 'dismissed' : ''}" data-task-key="${esc(t.key)}" data-task-link="${esc(link)}">
|
||||
<div class="post-task-body">
|
||||
${t.group_cover
|
||||
? `<button type="button" class="post-task-photo" data-img="${esc(API + t.group_cover)}" title="Открыть фото"><img src="${esc(thumbSrc(t.group_cover))}" alt="${esc(t.group_name)}" loading="lazy"></button>`
|
||||
@@ -133,7 +107,7 @@ function renderPostLessonTasks() {
|
||||
<div class="post-task-title">${esc(t.group_name)}<span class="post-task-date"> · ${esc(t.lesson_date)}</span></div>
|
||||
<div class="post-task-meta">${esc(t.lesson_time)}${t.tutor_name ? ' · ' + esc(t.tutor_name) : ''}</div>
|
||||
</div>
|
||||
<span class="post-task-badge ${badgeCls}">${badgeText}</span>
|
||||
<span class="post-task-badge ${badgeCls}">${badgeText}${isClosed && t.close_reason ? ' · ' + esc(t.close_reason) : ''}</span>
|
||||
</div>
|
||||
<div class="post-task-steps">
|
||||
${steps2.map((s, i) => {
|
||||
@@ -142,12 +116,13 @@ function renderPostLessonTasks() {
|
||||
const title = related.length
|
||||
? 'Короткие сообщения найдены, но не засчитаны: ' + related.map(r => r.resident + ' (' + r.lesson_date + (r.reason === 'date' ? ', другая дата' : ', другой автор') + ')').join('; ')
|
||||
: 'Нажмите, чтобы переключить статус';
|
||||
return `<span class="post-task-step ${s.done ? 'done' : ''} ${i === nextIdx ? 'next' : ''} ${s.manual ? 'manual' : ''} ${warn}" data-task-key="${esc(t.key)}" data-step-key="${esc(s.key)}" title="${esc(title)}">${s.done ? '✓' : (related.length ? '⚠' : '○')} ${esc(s.label)}${related.length ? ' (' + related.length + ')' : ''}</span>`;
|
||||
const reason = s.reason ? ' · причина: ' + esc(s.reason) : '';
|
||||
return `<span class="post-task-step ${s.done ? 'done' : ''} ${i === nextIdx ? 'next' : ''} ${s.manual ? 'manual' : ''} ${warn}" data-task-key="${esc(t.key)}" data-step-key="${esc(s.key)}" title="${esc(title)}${reason}">${s.done ? '✓' : (related.length ? '⚠' : '○')} ${esc(s.label)}${related.length ? ' (' + related.length + ')' : ''}</span>`;
|
||||
}).join('')}
|
||||
</div>
|
||||
${t.shorts_related && t.shorts_related.length && !(overrides[t.key] && overrides[t.key].shorts) ? `<div class="post-task-hint">Короткие сообщения найдены (${t.shorts_related.length}), но не засчитаны: ${t.shorts_related.map(r => esc(r.resident) + ' — ' + esc(r.lesson_date) + (r.reason === 'date' ? ' (другая дата)' : ' (другой автор)')).join(', ')}. Проверьте дату и автора.</div>` : ''}
|
||||
${t.shorts_related && t.shorts_related.length ? `<div class="post-task-hint">Короткие сообщения найдены (${t.shorts_related.length}), но не засчитаны: ${t.shorts_related.map(r => esc(r.resident) + ' — ' + esc(r.lesson_date) + (r.reason === 'date' ? ' (другая дата)' : ' (другой автор)')).join(', ')}. Проверьте дату и автора.</div>` : ''}
|
||||
<div class="post-task-actions">
|
||||
${isDismissed
|
||||
${isClosed
|
||||
? `<button type="button" class="btn-xs post-task-restore" data-restore-task="${esc(t.key)}" title="Вернуть задачу">Вернуть в работу</button>`
|
||||
: `<button type="button" class="btn-xs post-task-close" data-close-task="${esc(t.key)}" title="Закрыть задачу">Закрыть задачу</button>`}
|
||||
<button type="button" class="btn-xs post-task-detail" data-detail-task="${esc(t.key)}" title="Подробнее">Подробнее</button>
|
||||
@@ -190,27 +165,88 @@ function renderPager(total) {
|
||||
pager.innerHTML = html;
|
||||
}
|
||||
|
||||
function togglePostTaskStep(taskKey, stepKey) {
|
||||
const overrides = getPostTaskStepOverrides();
|
||||
if (!overrides[taskKey]) overrides[taskKey] = {};
|
||||
overrides[taskKey][stepKey] = !overrides[taskKey][stepKey];
|
||||
if (!overrides[taskKey][stepKey]) delete overrides[taskKey][stepKey];
|
||||
if (!Object.keys(overrides[taskKey]).length) delete overrides[taskKey];
|
||||
savePostTaskStepOverrides(overrides);
|
||||
renderPostLessonTasks();
|
||||
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();
|
||||
}
|
||||
|
||||
function dismissPostTask(key) {
|
||||
const dismissed = getPostTaskDismissed();
|
||||
dismissed.add(key);
|
||||
savePostTaskDismissed(dismissed);
|
||||
renderPostLessonTasks();
|
||||
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();
|
||||
}
|
||||
function restorePostTask(key) {
|
||||
const dismissed = getPostTaskDismissed();
|
||||
dismissed.delete(key);
|
||||
savePostTaskDismissed(dismissed);
|
||||
renderPostLessonTasks();
|
||||
|
||||
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(); });
|
||||
@@ -242,9 +278,7 @@ function openPostTaskDetail(taskKey) {
|
||||
const title = document.getElementById('plDetailTitle');
|
||||
const body = document.getElementById('plDetailBody');
|
||||
if (!modal || !title || !body) return;
|
||||
const overrides = getPostTaskStepOverrides();
|
||||
const taskOverride = overrides[t.key] || {};
|
||||
const steps = t.steps.map(s => ({ ...s, done: s.done || !!taskOverride[s.key], manual: !s.done && !!taskOverride[s.key] }));
|
||||
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}`;
|
||||
@@ -265,7 +299,9 @@ function openPostTaskDetail(taskKey) {
|
||||
html += `<span style="font-weight:600;font-size:13px">${s.done ? '✓' : '○'} ${esc(s.label)}</span>`;
|
||||
html += `<a class="btn-xs" href="${esc(s.link)}" title="Открыть раздел">Открыть</a>`;
|
||||
html += `</div>`;
|
||||
if (s.manual) html += `<div style="font-size:11px;opacity:.7;margin-bottom:4px">Отмечено вручную</div>`;
|
||||
if (s.manual) {
|
||||
html += `<div style="font-size:11px;opacity:.7;margin-bottom:4px">Отмечено вручную${s.reason ? ' — причина: ' + esc(s.reason) : ''}</div>`;
|
||||
}
|
||||
if (Array.isArray(s.basis) && s.basis.length) {
|
||||
html += `<div style="font-size:12px;opacity:.85">Основание:</div>`;
|
||||
html += `<ul style="margin:4px 0 0 16px;padding:0;font-size:12px">`;
|
||||
@@ -296,15 +332,35 @@ function closePostTaskDetail() {
|
||||
|
||||
const plList = document.getElementById('plList');
|
||||
if (plList) {
|
||||
plList.addEventListener('click', (e) => {
|
||||
plList.addEventListener('click', async (e) => {
|
||||
const closeBtn = e.target.closest('[data-close-task]');
|
||||
if (closeBtn) { e.stopPropagation(); dismissPostTask(closeBtn.dataset.closeTask); return; }
|
||||
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(); restorePostTask(restoreBtn.dataset.restoreTask); return; }
|
||||
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(); togglePostTaskStep(step.dataset.taskKey, step.dataset.stepKey); return; }
|
||||
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]');
|
||||
@@ -318,7 +374,30 @@ 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(); });
|
||||
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()) {
|
||||
|
||||
Reference in New Issue
Block a user