feat(dashboard): post-lesson tasks with blinking next step and manual close

This commit is contained in:
dev
2026-11-01 22:12:45 +03:00
parent 574f1bc204
commit b2f070ee7b
3 changed files with 270 additions and 0 deletions
+24
View File
@@ -5,6 +5,21 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Дашборд — Админ-панель</title>
<link rel="stylesheet" href="admin.css">
<style>
@keyframes postTaskBlink { 0%,100% { opacity:1; transform:scale(1); } 50% { opacity:.45; transform:scale(1.03); } }
.post-task { border-left:3px solid #f59e0b; padding:8px 10px; margin-bottom:10px; border-radius:8px; background:rgba(245,158,11,.05); }
.post-task.all-done { border-left-color:#22c55e; background:rgba(34,197,94,.05); opacity:.75; }
.post-task.overdue { border-left-color:#ef4444; background:rgba(239,68,68,.05); }
.post-task-head { display:flex; justify-content:space-between; gap:8px; align-items:center; margin-bottom:6px; }
.post-task-title { font-weight:600; font-size:13px; }
.post-task-meta { font-size:12px; opacity:.75; }
.post-task-steps { display:flex; flex-wrap:wrap; gap:6px; }
.post-task-step { display:inline-flex; align-items:center; gap:4px; padding:3px 8px; border-radius:999px; font-size:12px; background:rgba(0,0,0,.05); }
.post-task-step.done { color:#16a34a; text-decoration:line-through; opacity:.7; }
.post-task-step.next { animation:postTaskBlink 1.1s ease-in-out infinite; font-weight:600; background:rgba(245,158,11,.18); color:#b45309; }
.post-task-actions { display:flex; gap:6px; flex-wrap:wrap; margin-top:8px; }
.post-task-actions .btn-xs { padding:4px 10px; font-size:12px; }
</style>
</head>
<body data-page="dashboard">
<div class="layout">
@@ -60,6 +75,15 @@
<h3><span class="ic"><i data-lucide="activity"></i></span> Активные сейчас группы</h3>
<div class="active-list" id="activeList"></div>
</div>
<div class="dash-card">
<h3><span class="ic"><i data-lucide="list-checks"></i></span> Задачи после занятия</h3>
<div class="dash-list" id="postLessonTasks"></div>
<div class="post-task-actions">
<button type="button" class="btn-xs" id="closeDoneTasksBtn">Закрыть выполненные</button>
<button type="button" class="btn-xs" id="closeAllTasksBtn">Закрыть все</button>
</div>
<div class="dash-link-row"><span id="postLessonTasksSummary" class="dash-empty"></span></div>
</div>
<div class="dash-card">
<h3><span class="ic"><i data-lucide="trophy"></i></span> Топ учеников</h3>
<div class="top-list" id="topList"></div>
+112
View File
@@ -123,6 +123,80 @@ function renderPhotos(rows) {
</div>`).join('');
}
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) {}
}
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);
loadDashboard();
}
function dismissPostTask(key) {
const dismissed = getPostTaskDismissed();
dismissed.add(key);
savePostTaskDismissed(dismissed);
loadDashboard();
}
let currentPostTasks = [];
function renderPostLessonTasks(rows) {
const el = document.getElementById('postLessonTasks');
const summary = document.getElementById('postLessonTasksSummary');
if (!el) return;
const dismissed = getPostTaskDismissed();
const visible = (rows || []).filter(t => !dismissed.has(t.key));
currentPostTasks = visible;
if (!visible.length) {
el.innerHTML = '<div class="dash-empty">Нет задач после занятий</div>';
if (summary) summary.textContent = '';
return;
}
const pendingCount = visible.filter(t => !t.all_done).length;
const overdueCount = visible.filter(t => t.overdue && !t.all_done).length;
if (summary) summary.textContent = `Невыполненных: ${pendingCount} · просроченных: ${overdueCount}`;
const overrides = getPostTaskStepOverrides();
el.innerHTML = visible.map(t => {
const taskOverride = overrides[t.key] || {};
const steps = t.steps.map(s => ({ ...s, done: s.done || !!taskOverride[s.key] }));
const completed = steps.filter(s => s.done).length;
const allDone = completed === steps.length;
const nextIdx = steps.findIndex(s => !s.done);
const link = steps[nextIdx >= 0 ? nextIdx : 0].link;
return `
<div class="post-task ${allDone ? 'all-done' : ''} ${t.overdue && !allDone ? 'overdue' : ''}" data-task-key="${esc(t.key)}" data-task-link="${esc(link)}" style="cursor:pointer">
<div class="post-task-head">
<div>
<div class="post-task-title">${esc(t.group_name)} · ${esc(t.lesson_date)}</div>
<div class="post-task-meta">${esc(t.lesson_time)}${t.tutor_name ? ' · ' + esc(t.tutor_name) : ''}${t.overdue && !allDone ? ' · долг' : ''}</div>
</div>
<span class="top-count">${completed}/${steps.length}</span>
</div>
<div class="post-task-steps">
${steps.map((s, i) => `<span class="post-task-step ${s.done ? 'done' : ''} ${i === nextIdx ? 'next' : ''}" data-task-key="${esc(t.key)}" data-step-key="${esc(s.key)}" style="cursor:pointer" title="Нажмите, чтобы переключить статус">${s.done ? '✓' : '○'} ${esc(s.label)}</span>`).join('')}
</div>
<div class="post-task-actions">
<button type="button" class="btn-xs post-task-close" data-close-task="${esc(t.key)}" title="Закрыть задачу">Закрыть</button>
</div>
</div>`;
}).join('');
renderIcons();
}
function renderLessons(rows) {
const el = document.getElementById('lessonList');
if (!el) return;
@@ -153,6 +227,7 @@ async function loadDashboard() {
renderWorkMarks(d.work_marks || []);
renderPhotos(d.photos);
renderLessons(d.recent_lessons || []);
renderPostLessonTasks(d.post_lesson_tasks || []);
renderIcons();
}
@@ -170,6 +245,43 @@ document.addEventListener('click', e => {
if (item && !e.target.closest('button')) openLessonModal({ id: item.dataset.lesson });
});
const postTasksContainer = document.getElementById('postLessonTasks');
if (postTasksContainer) {
postTasksContainer.addEventListener('click', (e) => {
const closeBtn = e.target.closest('[data-close-task]');
if (closeBtn) {
e.stopPropagation();
dismissPostTask(closeBtn.dataset.closeTask);
return;
}
const step = e.target.closest('[data-step-key]');
if (step) {
e.stopPropagation();
togglePostTaskStep(step.dataset.taskKey, step.dataset.stepKey);
return;
}
const card = e.target.closest('.post-task[data-task-link]');
if (card && card.dataset.taskLink) {
window.location.href = card.dataset.taskLink;
}
});
}
const closeDoneTasksBtn = document.getElementById('closeDoneTasksBtn');
if (closeDoneTasksBtn) closeDoneTasksBtn.addEventListener('click', () => {
const dismissed = getPostTaskDismissed();
currentPostTasks.filter(t => t.all_done).forEach(t => dismissed.add(t.key));
savePostTaskDismissed(dismissed);
loadDashboard();
});
const closeAllTasksBtn = document.getElementById('closeAllTasksBtn');
if (closeAllTasksBtn) closeAllTasksBtn.addEventListener('click', () => {
const dismissed = getPostTaskDismissed();
currentPostTasks.forEach(t => dismissed.add(t.key));
savePostTaskDismissed(dismissed);
loadDashboard();
});
(async () => {
if (await checkAuth()) {
buildSidebar(document.body.dataset.page);
+134
View File
@@ -4512,6 +4512,7 @@ app.post('/api/feedbacks', requireAuth, asyncRoute(async (req, res) => {
await client.query('COMMIT');
await logAudit(req, 'feedback.create', { id: fb.id, group_id: groupId, resident, ai_check: aiCheck, ai_profile: aiProfile || null, ai_status: fb.ai_status, short_count: shortIds.length });
invalidateFeedbacks();
invalidateStats();
if (aiCheck) wakeFeedbackWorker();
res.status(201).json(fb);
} catch (e) {
@@ -5703,6 +5704,7 @@ app.put('/api/feedbacks/:id', requireAuth, asyncRoute(async (req, res) => {
client.release();
}
invalidateFeedbacks();
invalidateStats();
if (shortsTouched) invalidateShorts();
if (aiCheck) wakeFeedbackWorker();
await logAudit(req, 'feedback.update', { id, ai_check: aiCheck, ai_profile: aiProfile || null });
@@ -5737,6 +5739,7 @@ app.delete('/api/feedbacks/:id', requireAuth, async (req, res) => {
}
await logAudit(req, 'feedback.delete', { id });
invalidateFeedbacks();
invalidateStats();
if (shortsTouched) invalidateShorts();
res.json({ ok: true });
});
@@ -5767,6 +5770,7 @@ app.put('/api/feedbacks/:id/restore', requireAuth, async (req, res) => {
}
await logAudit(req, 'feedback.restore', { id });
invalidateFeedbacks();
invalidateStats();
if (shortsTouched) invalidateShorts();
res.json({ ok: true });
});
@@ -5797,6 +5801,7 @@ app.delete('/api/feedbacks/:id/permanent', requireAuth, async (req, res) => {
}
await logAudit(req, 'feedback.permanent-delete', { id });
invalidateFeedbacks();
invalidateStats();
if (shortsTouched) invalidateShorts();
res.json({ ok: true });
});
@@ -5828,6 +5833,7 @@ app.put('/api/feedbacks/:id/sent', requireAuth, async (req, res) => {
}
await logAudit(req, 'feedback.sent', { id, sent, short_count: shortIds.length });
invalidateFeedbacks();
invalidateStats();
if (shortsTouched) invalidateShorts();
res.json({ ok: true, sent });
} catch (err) {
@@ -9036,6 +9042,7 @@ app.post('/api/lesson-reports', requireAuth, async (req, res) => {
await saveLessonReportVersion(created.id, body, 'manual', req.user.id);
await logAudit(req, 'lesson_report.create', { id: created.id, group_id: grp.group.id, lesson_date: date, ai_status: created.ai_status });
invalidateLessonReports();
invalidateStats();
if (aiWanted) wakeLessonAiWorker();
await pushNotification({
type: 'lesson.report',
@@ -9110,6 +9117,7 @@ app.put('/api/lesson-reports/:id', requireAuth, async (req, res) => {
if (body) await saveLessonReportVersion(report.id, body, 'manual', req.user.id);
await logAudit(req, 'lesson_report.update', { id: report.id, group_id: nextGroup, lesson_date: date, ai_status: updated.ai_status });
invalidateLessonReports();
invalidateStats();
if (aiWanted) wakeLessonAiWorker();
res.json(updated);
});
@@ -9194,6 +9202,7 @@ app.delete('/api/lesson-reports/:id', requireAuth, async (req, res) => {
await pool.query('DELETE FROM lesson_reports WHERE id = $1', [report.id]);
await logAudit(req, 'lesson_report.delete', { id: report.id, group_id: report.group_id, lesson_date: report.lesson_date });
invalidateLessonReports();
invalidateStats();
res.json({ ok: true });
});
@@ -11833,6 +11842,128 @@ app.get('/api/setup/tls-package', requireAdmin, async (req, res) => {
}
});
async function buildPostLessonTasks(user) {
const isAdmin = user.role === 'admin';
const s = branchScope(user);
const branchIds = isAdmin ? [] : (s.ids || []);
if (!isAdmin && !user.id) return [];
let whereGroup = '';
const groupParams = [];
if (!isAdmin) {
whereGroup = ' AND g.tutor_id = $1';
groupParams.push(user.id);
}
const { rows: groups } = await pool.query(
`SELECT g.id, g.name, g.branch_id, g.tutor_id, g.day_of_week, g.time_start, g.time_end
FROM groups g
WHERE g.deleted_at IS NULL AND g.day_of_week IS NOT NULL AND g.time_start IS NOT NULL AND g.time_end IS NOT NULL${whereGroup}`,
groupParams
);
if (!groups.length) return [];
const tz = await appTimezone();
const today = await appTodayIso();
const { rows: nowRows } = await pool.query("SELECT to_char(now() AT TIME ZONE $1, 'HH24:MI') AS t", [tz]);
const nowHm = (nowRows[0] && nowRows[0].t) || '00:00';
const dates = [];
for (let i = 13; i >= 0; i--) {
const d = new Date(today + 'T00:00:00Z');
d.setUTCDate(d.getUTCDate() - i);
dates.push(d.toISOString().slice(0, 10));
}
const candidates = [];
for (const g of groups) {
for (const d of dates) {
const dow = new Date(d + 'T00:00:00Z').getUTCDay();
if (dow !== g.day_of_week) continue;
if (d > today) continue;
if (d === today) {
const end = String(g.time_end).slice(0, 5);
if (end > nowHm) continue;
}
candidates.push({ g, date: d });
}
}
if (!candidates.length) return [];
const groupIds = [...new Set(candidates.map(c => c.g.id))];
const dateList = [...new Set(candidates.map(c => c.date))];
const reportSet = new Set();
const { rows: reportRows } = await pool.query(
`SELECT group_id, lesson_date::text AS d FROM lesson_reports WHERE group_id = ANY($1::int[]) AND lesson_date = ANY($2::date[])`,
[groupIds, dateList]
);
reportRows.forEach(r => reportSet.add(r.group_id + '|' + r.d));
const feedbackSet = new Set();
const { rows: fbRows } = await pool.query(
`SELECT group_id, feedback_date::text AS d FROM feedbacks WHERE deleted_at IS NULL AND group_id = ANY($1::int[]) AND feedback_date = ANY($2::date[])`,
[groupIds, dateList]
);
fbRows.forEach(r => feedbackSet.add(r.group_id + '|' + r.d));
const { rows: students } = await pool.query(
`SELECT name, group_id FROM students WHERE group_id = ANY($1::int[]) AND deleted_at IS NULL`,
[groupIds]
);
const studentsByGroup = new Map();
for (const st of students) {
if (!studentsByGroup.has(st.group_id)) studentsByGroup.set(st.group_id, []);
studentsByGroup.get(st.group_id).push(String(st.name || '').trim().toLowerCase());
}
const groupsByStudentName = new Map();
for (const g of groups) {
for (const name of (studentsByGroup.get(g.id) || [])) {
if (!groupsByStudentName.has(name)) groupsByStudentName.set(name, new Set());
groupsByStudentName.get(name).add(g.id);
}
}
const shortsSet = new Set();
const { rows: shortRows } = await pool.query(
`SELECT lesson_date::text AS d, resident FROM short_messages WHERE deleted_at IS NULL AND lesson_date = ANY($1::date[])`,
[dateList]
);
for (const sm of shortRows) {
const gids = groupsByStudentName.get(String(sm.resident || '').trim().toLowerCase());
if (gids) for (const gid of gids) shortsSet.add(gid + '|' + sm.d);
}
const tutorIds = [...new Set(groups.map(g => g.tutor_id).filter(Boolean))];
const tutorMap = new Map();
if (tutorIds.length) {
const { rows: users } = await pool.query('SELECT id, name, username FROM users WHERE id = ANY($1::int[])', [tutorIds]);
for (const u of users) tutorMap.set(u.id, u.name || u.username || '');
}
const tasks = candidates.map(({ g, date }) => {
const key = g.id + '|' + date;
const reportDone = reportSet.has(key);
const shortsDone = shortsSet.has(key);
const feedbackDone = feedbackSet.has(key);
const steps = [
{ key: 'report', label: 'Отчёт о занятии', done: reportDone, link: '/lessons.html' },
{ key: 'shorts', label: 'Короткие сообщения', done: shortsDone, link: '/shorts.html' },
{ key: 'feedback', label: 'Обратная связь', done: feedbackDone, link: '/feedback.html' },
];
const completed = steps.filter(x => x.done).length;
return {
key,
group_id: g.id,
group_name: g.name,
tutor_id: g.tutor_id || null,
tutor_name: g.tutor_id ? (tutorMap.get(g.tutor_id) || '') : '',
lesson_date: date,
lesson_time: String(g.time_start).slice(0, 5) + '–' + String(g.time_end).slice(0, 5),
steps,
completed,
total: 3,
overdue: date < today,
all_done: completed === 3,
};
});
tasks.sort((a, b) => {
if (a.all_done !== b.all_done) return a.all_done ? 1 : -1;
if (a.overdue !== b.overdue) return a.overdue ? -1 : 1;
if (a.lesson_date !== b.lesson_date) return b.lesson_date.localeCompare(a.lesson_date);
return String(a.group_name).localeCompare(String(b.group_name));
});
return tasks;
}
app.get('/api/dashboard', requireAuth, async (req, res) => {
try {
const payload = await cacheWrap('dashboard:' + scopeKey(req.user), STATS_TTL_MS, async () => {
@@ -11948,6 +12079,7 @@ app.get('/api/dashboard', requireAuth, async (req, res) => {
recent_lessons: lessons.rows,
work_marks: marks.rows,
latest_photo_taken: (latestPhotos.rows[0] || {}).taken_at || null,
post_lesson_tasks: await buildPostLessonTasks(req.user),
disk: getDiskInfo(),
};
});
@@ -14112,6 +14244,7 @@ apiV1.post('/lesson-reports', apiWrite('write'), async (req, res) => {
await saveLessonReportVersion(created.id, text, 'manual', req.user.id);
await apiAudit(req, 'api.lesson_report.create', { id: created.id, group_id: grp.group.id, lesson_date: date });
invalidateLessonReports();
invalidateStats();
if (aiWanted) wakeLessonAiWorker();
res.status(201).json(created);
});
@@ -14163,6 +14296,7 @@ apiV1.put('/lesson-reports/:id', apiWrite('write'), async (req, res) => {
if (body) await saveLessonReportVersion(report.id, body, 'manual', req.user.id);
await apiAudit(req, 'api.lesson_report.update', { id: report.id, lesson_date: date });
invalidateLessonReports();
invalidateStats();
if (aiWanted) wakeLessonAiWorker();
res.json(rows[0]);
});