Files
jwxt/app/templates/tasks.html
T

729 lines
44 KiB
HTML

{% extends "base_tailwind.html" %}
{% block title %}抢课任务 - 教务抢课系统{% endblock %}
{% block extra_css %}
<style>
/* 任务详情模态框动画 */
#taskDetailModal {
transition: opacity 0.24s ease;
}
/* 增量刷新闪烁高亮 */
@keyframes cellFlash {
0% { background-color: rgba(34, 197, 94, 0.25); }
100% { background-color: transparent; }
}
.cell-flash {
animation: cellFlash 0.8s ease-out;
border-radius: 4px;
}
.dark .cell-flash {
animation-name: cellFlashDark;
}
@keyframes cellFlashDark {
0% { background-color: rgba(34, 197, 94, 0.3); }
100% { background-color: transparent; }
}
@media (prefers-reduced-motion: reduce) {
.cell-flash, .dark .cell-flash { animation: none !important; }
}
</style>
{% endblock %}
{% block content %}
<div>
<!-- 页面标题 -->
<div class="flex justify-between items-center mb-6 list-item-enter" style="animation-delay: 0ms;">
<h2 class="text-2xl font-bold flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
抢课任务管理
</h2>
<a href="{{ url_for('main.courses') }}"
class="px-6 py-2 bg-black dark:bg-white text-white dark:text-black rounded-full font-medium hover:opacity-80 transition-opacity flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
新建任务
</a>
</div>
<!-- 管理员查看其他用户任务的提示 -->
<div id="viewingUserBanner" class="hidden mb-4">
<div class="glass rounded-2xl px-4 py-3 flex items-center gap-3 text-sm">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-blue-500 flex-shrink-0"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
<span>正在查看 <strong id="viewingUserName">用户</strong> 的任务列表</span>
<a href="/tasks" class="ml-auto px-3 py-1 rounded-full bg-black dark:bg-white text-white dark:text-black text-xs font-medium hover:opacity-80 transition-opacity">返回我的任务</a>
</div>
</div>
<!-- 筛选栏 -->
<div class="glass rounded-2xl p-4 sm:p-6 mb-4 sm:mb-6 list-item-enter" style="animation-delay: 50ms;">
<div class="flex flex-col sm:flex-row gap-3 sm:gap-4 items-stretch sm:items-center">
<div class="flex-1">
<div class="relative">
<select id="statusFilter" onchange="loadTasks()"
class="w-full sm:w-64 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-black focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white appearance-none text-sm">
<option value="">📋 全部状态</option>
<option value="pending">⏳ 待执行</option>
<option value="running">🔄 执行中</option>
<option value="success">✅ 成功</option>
<option value="failed">❌ 失败</option>
<option value="cancelled">🚫 已取消</option>
</select>
<span class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
</span>
</div>
</div>
<div class="flex gap-2 items-center">
<span id="autoRefreshBadge" class="hidden text-xs text-gray-400 flex items-center gap-1">
<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span>
自动刷新中
</span>
<button onclick="loadTasks(1)"
class="btn-outline text-sm px-4 py-2">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 21h5v-5"/></svg>
刷新
</button>
</div>
</div>
</div>
<!-- 任务列表 -->
<div class="glass rounded-2xl p-4 sm:p-6 list-item-enter" style="animation-delay: 100ms;">
<div id="loadingIndicator" class="text-center py-12">
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
<p class="text-gray-500 dark:text-gray-400">加载中...</p>
</div>
<div id="emptyState" class="text-center py-12" style="display: none;">
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-400"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
</div>
<p class="text-gray-500 dark:text-gray-400 mb-1 font-medium">暂无任务</p>
<p class="text-sm text-gray-400 dark:text-gray-500 mb-5">去课程列表创建你的第一个抢课任务</p>
<a href="{{ url_for('main.courses') }}"
class="inline-flex items-center gap-2 px-6 py-2.5 bg-black dark:bg-white text-white dark:text-black rounded-full font-medium hover:opacity-80 transition-all hover:shadow-lg">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
创建任务
</a>
</div>
<div id="tasksTableContainer" class="max-w-5xl mx-auto" style="display: none;">
<div class="-mx-2 sm:mx-0">
<table class="card-on-mobile data-table w-full">
<thead>
<tr>
<th>ID</th>
<th>课程名称</th>
<th>教师</th>
<th>类型</th>
<th>状态</th>
<th>重试</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tasksTableBody">
</tbody>
</table>
</div>
</div>
<!-- 分页 -->
<nav id="pagination" class="mt-4 sm:mt-6" style="display: none;">
<div class="flex justify-center items-center gap-1.5 sm:gap-2">
</div>
</nav>
</div>
</div>
<!-- 任务详情模态框 -->
<div id="taskDetailModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 opacity-0 pointer-events-none transition-opacity duration-300">
<div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeTaskDetailModal()"></div>
<div class="relative w-full max-w-3xl p-4">
<div class="glass rounded-2xl p-6 max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
<div class="flex justify-between items-center mb-6">
<h3 class="text-xl font-bold flex items-center gap-2">
<div class="w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
</div>
任务详情
</h3>
<button onclick="closeTaskDetailModal()" class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
</button>
</div>
<div id="taskDetailLoading" class="text-center py-8">
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
</div>
<div id="taskDetailContent" style="display: none;">
<div class="overflow-x-auto mb-6">
<table class="w-full">
<tbody class="divide-y divide-gray-200 dark:divide-gray-700">
<tr><td class="py-3 text-gray-500 dark:text-gray-400 w-32">课程名称</td><td id="detailCourseName" class="py-3 font-medium"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">教学班</td><td id="detailClassInfo" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">教师</td><td id="detailTeacher" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">学分</td><td id="detailCredit" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">任务类型</td><td id="detailType" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">状态</td><td id="detailStatus" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">重试次数</td><td id="detailRetries" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">创建时间</td><td id="detailCreated" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">开始时间</td><td id="detailStarted" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">完成时间</td><td id="detailCompleted" class="py-3"></td></tr>
<tr><td class="py-3 text-gray-500 dark:text-gray-400">结果消息</td><td id="detailMessage" class="py-3"></td></tr>
</tbody>
</table>
</div>
<!-- 自定义规则展示 -->
<div id="detailRulesContainer" class="mb-6 hidden">
<h6 class="font-semibold mb-3 flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
自定义规则
</h6>
<div id="detailRulesBody" class="space-y-2"></div>
</div>
<h6 class="font-semibold mb-3 flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
实时日志
</h6>
<div id="taskLogs" class="scrollbar-thin space-y-1.5 max-h-[300px] overflow-y-auto font-mono text-sm p-3 sm:p-4 rounded-xl bg-white/50 dark:bg-black/30 border border-gray-200 dark:border-gray-700">
<!-- 日志内容 -->
</div>
</div>
<div class="flex gap-3 justify-end mt-6">
<button onclick="closeTaskDetailModal()"
class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-full hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
关闭
</button>
<button id="cancelTaskBtn" onclick="cancelCurrentTask()" style="display: none;"
class="px-6 py-2 bg-red-600 text-white rounded-full font-medium hover:bg-red-700 transition-colors flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
取消任务
</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script>
let currentPage = 1;
let currentTaskId = null;
let logRefreshInterval = null;
let lastLogId = 0;
// 管理员查看指定用户的任务
const viewingUserId = new URLSearchParams(window.location.search).get('user_id') || '';
function openTaskDetailModal() {
const modal = document.getElementById('taskDetailModal');
modal.classList.remove('opacity-0', 'pointer-events-none');
modal.classList.add('opacity-100', 'pointer-events-auto');
document.documentElement.style.overflow = 'hidden';
document.body.style.overflow = 'hidden';
}
function closeTaskDetailModal() {
const modal = document.getElementById('taskDetailModal');
modal.classList.add('opacity-0', 'pointer-events-none');
modal.classList.remove('opacity-100', 'pointer-events-auto');
document.documentElement.style.overflow = '';
document.body.style.overflow = '';
if (logRefreshInterval) {
clearInterval(logRefreshInterval);
logRefreshInterval = null;
}
}
// 加载任务列表
async function loadTasks(page = 1) {
currentPage = page;
const status = document.getElementById('statusFilter').value;
document.getElementById('loadingIndicator').style.display = 'block';
document.getElementById('emptyState').style.display = 'none';
document.getElementById('tasksTableContainer').style.display = 'none';
document.getElementById('pagination').style.display = 'none';
try {
let url = `/api/tasks/list?page=${page}&per_page=20`;
if (status) url += `&status=${status}`;
const data = await apiRequest(url);
document.getElementById('loadingIndicator').style.display = 'none';
if (!data.success || !data.tasks || data.tasks.length === 0) {
document.getElementById('emptyState').style.display = 'block';
if (viewingUserId) {
// 管理员查看他人任务:即使空也显示表格区域,方便看横幅
document.getElementById('tasksTableContainer').style.display = 'block';
}
return;
}
renderTasksTable(data.tasks);
renderPagination(data.total, data.pages, page);
document.getElementById('tasksTableContainer').style.display = 'block';
document.getElementById('pagination').style.display = 'block';
// 显示自动刷新 badge
const badge = document.getElementById('autoRefreshBadge');
if (badge) badge.classList.remove('hidden');
// 管理员查看其他用户:显示横幅
if (viewingUserId) {
document.getElementById('viewingUserBanner')?.classList.remove('hidden');
const nameEl = document.getElementById('viewingUserName');
if (data.tasks && data.tasks.length > 0 && data.tasks[0].username) {
nameEl.textContent = data.tasks[0].username;
} else {
nameEl.textContent = 'ID ' + viewingUserId;
}
}
} catch (error) {
document.getElementById('loadingIndicator').style.display = 'none';
if (!silent) showToast('加载失败,请稍后重试', 'error');
}
}
// 渲染任务表格
function renderTasksTable(tasks) {
const tbody = document.getElementById('tasksTableBody');
tbody.innerHTML = tasks.map((task, index) => {
const typeBadge = task.task_type === 'immediate'
? '<span class="status-badge status-info"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg> 立即</span>'
: '<span class="status-badge status-warning"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> 定时</span>';
const delay = Math.min(index * 30, 300);
return `
<tr data-task-id="${task.id}" class="list-item-enter" style="animation-delay: ${delay}ms;">
<td data-label="ID"><span class="font-mono text-xs sm:text-sm text-gray-500 dark:text-gray-400">#${task.id}</span></td>
<td data-label="课程名称"><strong class="text-sm">${escapeHtml(task.course_name)}</strong></td>
<td data-label="教师"><span class="text-sm">${escapeHtml(task.teacher_name || '-')}</span></td>
<td data-label="类型">${typeBadge}</td>
<td data-label="状态" class="task-status-cell">${getStatusBadge(task.status)}</td>
<td data-label="重试" class="task-retry-cell"><span class="text-xs sm:text-sm">${task.retry_count}/${task.max_retries === 0 ? '∞' : task.max_retries}</span></td>
<td data-label="创建时间"><span class="text-xs sm:text-sm text-gray-500">${formatTime(task.created_at)}</span></td>
<td data-label="操作" class="task-actions-cell">
<div class="flex gap-1.5 sm:gap-2">
<button onclick="viewTaskDetail(${task.id})"
class="p-1.5 sm:p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" title="查看详情">
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
${(task.status === 'pending' || task.status === 'running') ? `
<button onclick="cancelTask(${task.id})"
class="p-1.5 sm:p-2 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors" title="取消任务">
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
</button>
` : ''}
</div>
</td>
</tr>
`;
}).join('');
}
// ── 增量刷新(只更新变化的单元格) ──
let _refreshCount = 0;
async function incrementalRefresh() {
// 仅当表格可见时才刷新
const container = document.getElementById('tasksTableContainer');
if (!container || container.style.display === 'none') return;
const status = document.getElementById('statusFilter').value;
try {
const data = await apiRequest(getTaskListUrl(currentPage) + (status ? '&status=' + status : ''));
if (!data.success || !data.tasks) return;
const tbody = document.getElementById('tasksTableBody');
const existingRows = tbody.querySelectorAll('tr[data-task-id]');
const existingMap = {};
existingRows.forEach(tr => { existingMap[tr.getAttribute('data-task-id')] = tr; });
let changed = false;
data.tasks.forEach((task, idx) => {
const tid = String(task.id);
const oldRow = existingMap[tid];
if (oldRow) {
// 行存在 → 增量更新单元格
if (updateCellIfChanged(oldRow, '.task-status-cell', getStatusBadge(task.status))) changed = true;
if (updateCellIfChanged(oldRow, '.task-retry-cell',
'<span class="text-xs sm:text-sm">' + task.retry_count + '/' + (task.max_retries === 0 ? '∞' : task.max_retries) + '</span>')) changed = true;
// 操作列:如果状态从 pending/running 变了,需隐藏取消按钮
const actionsCell = oldRow.querySelector('.task-actions-cell');
const newActionsHtml = buildActionsHtml(task);
if (actionsCell && actionsCell.innerHTML.trim() !== newActionsHtml.trim()) {
actionsCell.innerHTML = newActionsHtml;
changed = true;
}
} else {
// 新任务出现在本页 → 插入
changed = true;
}
});
if (changed) {
_refreshCount++;
const badge = document.getElementById('autoRefreshBadge');
if (badge) {
badge.classList.remove('hidden');
badge.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span> 已更新';
clearTimeout(badge._hideTimer);
badge._hideTimer = setTimeout(() => {
badge.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span> 自动刷新中';
}, 2000);
}
}
} catch (e) {
// 静默失败
}
}
// ── 辅助:仅当值不同时才更新 DOM,并附带闪烁反馈 ──
function updateCellIfChanged(row, selector, newHtml) {
const cell = row.querySelector(selector);
if (!cell) return false;
const old = cell.innerHTML.trim();
if (old === newHtml.trim()) return false;
cell.innerHTML = newHtml;
// 闪烁高亮
cell.classList.remove('cell-flash');
void cell.offsetWidth; // 强制 reflow
cell.classList.add('cell-flash');
setTimeout(() => cell.classList.remove('cell-flash'), 800);
return true;
}
// ── 辅助:构建操作列 HTML ──
function buildActionsHtml(task) {
const viewBtn = '<button onclick="viewTaskDetail(' + task.id + ')" class="p-1.5 sm:p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" title="查看详情"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg></button>';
const cancelBtn = (task.status === 'pending' || task.status === 'running')
? '<button onclick="cancelTask(' + task.id + ')" class="p-1.5 sm:p-2 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors" title="取消任务"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg></button>'
: '';
return '<div class="flex gap-1.5 sm:gap-2">' + viewBtn + cancelBtn + '</div>';
}
function getTaskListUrl(page) {
let url = `/api/tasks/list?page=${page}&per_page=20`;
if (viewingUserId) url += `&user_id=${viewingUserId}`;
return url;
}
// 加载任务列表(全量,仅手动调用时触发 loading) ──
async function loadTasks(page = 1, silent = false) {
currentPage = page;
const status = document.getElementById('statusFilter').value;
if (!silent) {
document.getElementById('loadingIndicator').style.display = 'block';
document.getElementById('emptyState').style.display = 'none';
document.getElementById('tasksTableContainer').style.display = 'none';
document.getElementById('pagination').style.display = 'none';
}
try {
let url = getTaskListUrl(page);
if (status) url += `&status=${status}`;
const data = await apiRequest(url);
if (!silent) {
document.getElementById('loadingIndicator').style.display = 'none';
}
if (!data.success || !data.tasks || data.tasks.length === 0) {
document.getElementById('emptyState').style.display = 'block';
document.getElementById('tasksTableContainer').style.display = 'none';
return;
}
renderTasksTable(data.tasks);
renderPagination(data.total, data.pages, page);
document.getElementById('tasksTableContainer').style.display = 'block';
document.getElementById('pagination').style.display = 'block';
// 显示自动刷新 badge
const badge = document.getElementById('autoRefreshBadge');
if (badge) badge.classList.remove('hidden');
} catch (error) {
if (!silent) {
document.getElementById('loadingIndicator').style.display = 'none';
showToast('加载失败,请稍后重试', 'error');
}
}
}
function renderPagination(total, pages, current) {
const nav = document.getElementById('pagination').querySelector('div');
let html = '';
html += `
<button onclick="loadTasks(${current - 1})" ${current === 1 ? 'disabled' : ''}
class="px-2.5 sm:px-3 py-1.5 text-xs sm:text-sm rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>
<span class="hidden sm:inline">上一页</span>
</button>
`;
for (let i = 1; i <= pages; i++) {
if (i === 1 || i === pages || (i >= current - 2 && i <= current + 2)) {
html += `
<button onclick="loadTasks(${i})"
class="min-w-[32px] sm:min-w-[36px] h-8 sm:h-9 rounded-lg text-xs sm:text-sm font-medium transition-all ${i === current ? 'bg-black dark:bg-white text-white dark:text-black shadow-sm' : 'border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800'}">
${i}
</button>
`;
} else if (i === current - 3 || i === current + 3) {
html += `<span class="px-1 sm:px-2 text-gray-400 text-xs sm:text-sm">…</span>`;
}
}
html += `
<button onclick="loadTasks(${current + 1})" ${current === pages ? 'disabled' : ''}
class="px-2.5 sm:px-3 py-1.5 text-xs sm:text-sm rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1">
<span class="hidden sm:inline">下一页</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
</button>
`;
nav.innerHTML = html;
}
// 查看任务详情
async function viewTaskDetail(taskId) {
currentTaskId = taskId;
lastLogId = 0;
document.getElementById('taskDetailLoading').style.display = 'block';
document.getElementById('taskDetailContent').style.display = 'none';
document.getElementById('cancelTaskBtn').style.display = 'none';
openTaskDetailModal();
// 清除之前的定时器
if (logRefreshInterval) {
clearInterval(logRefreshInterval);
}
try {
const data = await apiRequest(`/api/tasks/${taskId}`);
document.getElementById('taskDetailLoading').style.display = 'none';
document.getElementById('taskDetailContent').style.display = 'block';
if (data.success) {
const task = data.task;
document.getElementById('detailCourseName').textContent = task.course_name;
document.getElementById('detailClassInfo').textContent = task.class_info || '-';
document.getElementById('detailTeacher').textContent = task.teacher_name || '-';
document.getElementById('detailCredit').textContent = task.credit || '-';
document.getElementById('detailType').innerHTML = task.task_type === 'immediate'
? '<span class="status-badge status-info"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg> 立即抢课</span>'
: '<span class="status-badge status-warning"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> 定时抢课</span> <span class="text-xs text-gray-400">(' + formatTime(task.scheduled_time) + ')</span>';
document.getElementById('detailStatus').innerHTML = getStatusBadge(task.status);
document.getElementById('detailRetries').textContent = `${task.retry_count}/${task.max_retries}`;
document.getElementById('detailCreated').textContent = formatTime(task.created_at);
document.getElementById('detailStarted').textContent = formatTime(task.started_at);
document.getElementById('detailCompleted').textContent = formatTime(task.completed_at);
document.getElementById('detailMessage').textContent = task.result_message || '-';
// 显示自定义规则
renderTaskRules(task.rules);
// 显示取消按钮
if (task.status === 'pending' || task.status === 'running') {
document.getElementById('cancelTaskBtn').style.display = 'inline-flex';
}
// 加载日志
loadTaskLogs(taskId);
// 如果任务正在运行,定时刷新日志
if (task.status === 'running') {
logRefreshInterval = setInterval(() => loadTaskLogs(taskId, true), 2000);
}
}
} catch (error) {
document.getElementById('taskDetailLoading').style.display = 'none';
showToast('加载详情失败', 'error');
}
}
// 加载任务日志
async function loadTaskLogs(taskId, incremental = false) {
try {
let url = `/api/logs/list?task_id=${taskId}&per_page=100`;
if (incremental && lastLogId > 0) {
url = `/api/logs/recent?task_id=${taskId}&after_id=${lastLogId}`;
}
const data = await apiRequest(url);
if (data.success && data.logs) {
const logContainer = document.getElementById('taskLogs');
if (!incremental) {
logContainer.innerHTML = '';
}
const levelColors = {
'info': 'text-blue-600 dark:text-blue-400',
'success': 'text-green-600 dark:text-green-400',
'warning': 'text-yellow-600 dark:text-yellow-400',
'error': 'text-red-600 dark:text-red-400'
};
data.logs.forEach(log => {
if (log.id > lastLogId) {
lastLogId = log.id;
}
const logClass = levelColors[log.level] || 'text-gray-600 dark:text-gray-400';
const logHtml = `
<div class="p-2 rounded-lg bg-white/50 dark:bg-black/30">
<span class="text-gray-400 text-xs">${log.created_at ? formatTime(log.created_at).split(' ').slice(1).join(' ') : ''}</span>
<span class="${logClass} font-bold text-xs">[${log.level.toUpperCase()}]</span>
${escapeHtml(log.message)}
</div>
`;
logContainer.insertAdjacentHTML('beforeend', logHtml);
});
// 滚动到底部
logContainer.scrollTop = logContainer.scrollHeight;
}
} catch (error) {
console.error('加载日志失败:', error);
}
}
// 取消任务
async function cancelTask(taskId) {
if (!confirm('确定要取消这个任务吗?')) return;
try {
const data = await apiRequest(`/api/tasks/${taskId}/cancel`, {
method: 'POST'
});
if (data.success) {
showToast('任务已取消', 'success');
loadTasks(currentPage);
} else {
showToast(data.message || '取消失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
}
// 取消当前查看的任务
async function cancelCurrentTask() {
if (currentTaskId) {
await cancelTask(currentTaskId);
closeTaskDetailModal();
}
}
// HTML转义
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// ── SVG 图标(用于状态徽章) ──
const ICONS = {
pending: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><path d="M12 2v6l4 4-4 4v6"/><path d="M4 2h16"/><path d="M4 22h16"/></svg>',
running: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5 animate-spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',
success: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
failed: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',
cancelled: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/></svg>',
expired: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
unknown: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>',
};
// ── 渲染自定义规则 ──
function renderTaskRules(rules) {
const container = document.getElementById('detailRulesContainer');
const body = document.getElementById('detailRulesBody');
if (!container || !body) return;
if (!rules || !rules.on_has_vacancy || rules.on_has_vacancy.length === 0) {
container.classList.add('hidden');
return;
}
container.classList.remove('hidden');
body.innerHTML = rules.on_has_vacancy.map((rule, i) => {
if (rule.action === 'drop_course') {
return `
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-emerald-50/80 dark:bg-emerald-950/20 border border-emerald-200 dark:border-emerald-800">
<span class="flex-shrink-0 w-6 h-6 rounded-md bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 flex items-center justify-center text-xs font-bold">${i + 1}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-emerald-600 dark:text-emerald-400"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
<span class="text-sm font-medium text-emerald-800 dark:text-emerald-200">退课</span>
<span class="text-sm text-gray-600 dark:text-gray-400">${escapeHtml(rule.course_name || '未知课程')}</span>
<span class="text-xs text-gray-400 dark:text-gray-500 ml-auto">抢课前执行</span>
</div>
`;
}
if (rule.action === 'wait') {
return `
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-blue-50/80 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800">
<span class="flex-shrink-0 w-6 h-6 rounded-md bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 flex items-center justify-center text-xs font-bold">${i + 1}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-blue-600 dark:text-blue-400"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
<span class="text-sm font-medium text-blue-800 dark:text-blue-200">等待</span>
<span class="text-sm text-gray-600 dark:text-gray-400">${rule.seconds || 2} 秒</span>
</div>
`;
}
return '';
}).join('') + `
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-gray-100/80 dark:bg-gray-800/60 border border-dashed border-gray-300 dark:border-gray-700">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-gray-500"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
<span class="text-sm text-gray-500 dark:text-gray-400">→ 然后自动抢课</span>
</div>
`;
}
// 状态徽章
function getStatusBadge(status) {
const statusMap = {
'pending': { class: 'status-pending', icon: ICONS.pending, text: '待执行' },
'running': { class: 'status-running', icon: ICONS.running, text: '执行中' },
'success': { class: 'status-success', icon: ICONS.success, text: '成功' },
'failed': { class: 'status-failed', icon: ICONS.failed, text: '失败' },
'cancelled': { class: 'status-cancelled', icon: ICONS.cancelled, text: '已取消' },
'expired': { class: 'status-cancelled', icon: ICONS.expired, text: '已过期' }
};
const s = statusMap[status] || { class: 'status-pending', icon: ICONS.unknown, text: status };
return '<span class="status-badge ' + s.class + '">' + s.icon + s.text + '</span>';
}
// 页面加载
document.addEventListener('DOMContentLoaded', function() {
// 将弹窗移到 body 直接子级,确保 fixed 定位基于视口
const taskDetailModal = document.getElementById('taskDetailModal');
if (taskDetailModal) document.body.appendChild(taskDetailModal);
loadTasks();
// 每5秒增量刷新(只更新变化的单元格,不重绘整表)
setInterval(() => incrementalRefresh(), 5000);
});
</script>
{% endblock %}