fix: 整理首页、登录和管理端的交互

This commit is contained in:
2026-11-16 03:18:08 +08:00
parent c9f70ad455
commit 2fb40c37ae
19 changed files with 1117 additions and 423 deletions
+98 -62
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, HelpCircleOutline, PlayOutline, RefreshOutline, StopOutline, WarningOutline } from "@vicons/ionicons5";
import { dayOptions, workerHint, workerOptions } from "../../shared/studyFields";
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline, WarningOutline } from "@vicons/ionicons5";
import { dayOptions, workerOptions } from "../../shared/studyFields";
interface HomeSummary {
name: string;
@@ -26,6 +26,7 @@ interface StudyWorker {
sent: number;
total: number;
ok: boolean;
finished: boolean;
}
type SectionState = "loading" | "ready" | "error";
@@ -35,6 +36,7 @@ const summary = ref<HomeSummary | null>(null);
const summaryState = ref<SectionState>("loading");
const summaryError = ref("");
const refreshing = ref(false);
const avatarBroken = ref(false);
let refreshRunning = false;
let busy = false;
let studyTick = 0;
@@ -68,7 +70,7 @@ const studyBusy = ref(false);
const studyError = ref("");
const studyingWorkers = computed(() => (
studyControl.value.workers.filter((row) => row.course.trim() && workerPercent(row) < 100)
studyControl.value.workers.filter((row) => row.course.trim() && !workerDone(row))
));
const countdownOn = computed(() => (
@@ -121,20 +123,48 @@ function amount(value: string | number | null | undefined) {
return String(value);
}
function withMinutes(value: string) {
if (!value || value === "—") return "—";
return `${value} 分钟`;
}
const facts = computed(() => {
const current = summary.value;
return [
{ label: "本年学时", value: current ? amount(current.year_hours) : "" },
{ label: "本月学时", value: current ? amount(current.month_hours) : "" },
{ label: "今日学时", value: current ? amount(current.today_hours) : "" },
{ label: "累计学时", value: current ? amount(current.total_hours) : "" },
{ label: "本年学时", value: current ? withMinutes(amount(current.year_hours)) : "" },
{ label: "本月学时", value: current ? withMinutes(amount(current.month_hours)) : "" },
{ label: "本日学时", value: current ? withMinutes(amount(current.today_hours)) : "" },
{ label: "总学时", value: current ? withMinutes(amount(current.total_hours)) : "" },
{ label: "累计学分", value: current ? amount(current.total_score) : "" },
{ label: "可用积分", value: current ? amount(current.points) : "" },
];
});
function failureText(payload: { detail?: unknown }, fallback: string) {
return typeof payload.detail === "string" ? payload.detail : fallback;
const detail = payload.detail;
if (typeof detail !== "string" || !detail.trim()) return fallback;
if (/traceback|exception|sqlite|httpx|errno|timeout|error:/i.test(detail)) return fallback;
return detail;
}
function asSummary(value: unknown): HomeSummary | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
const known = ["name", "month_hours", "year_hours", "total_hours", "today_hours"].some((key) => key in row);
if (!known) return null;
const text = (key: string) => (typeof row[key] === "string" || typeof row[key] === "number" ? row[key] : "");
return {
name: typeof row.name === "string" ? row.name : "",
avatar: typeof row.avatar === "string" ? row.avatar : "",
department: typeof row.department === "string" ? row.department : "",
level: typeof row.level === "string" ? row.level : "",
year_hours: String(text("year_hours") ?? ""),
month_hours: String(text("month_hours") ?? ""),
today_hours: typeof row.today_hours === "number" || typeof row.today_hours === "string" ? row.today_hours : null,
total_hours: String(text("total_hours") ?? ""),
total_score: String(text("total_score") ?? ""),
points: typeof row.points === "number" || typeof row.points === "string" ? row.points : null,
};
}
function pad(value: number) {
@@ -156,13 +186,19 @@ function asWorkers(value: unknown): StudyWorker[] {
sent: typeof row.sent === "number" ? row.sent : 0,
total: typeof row.total === "number" ? row.total : 0,
ok: row.ok !== false,
finished: row.finished === true || row.completed === true || row.done === true,
});
}
return rows;
}
function workerDone(row: StudyWorker) {
return row.finished || row.progress >= 100;
}
function workerPercent(row: StudyWorker) {
return Math.min(100, Math.max(0, Math.round(row.progress)));
if (workerDone(row)) return 100;
return Math.min(99, Math.max(0, Math.floor(row.progress)));
}
function workerTitle(row: StudyWorker) {
@@ -201,20 +237,23 @@ async function loadSummary() {
const response = await fetch("/api/home/summary");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
if (!hadData) {
summaryError.value = failureText(payload, "个人学习信息没有获取到。");
summaryState.value = "error";
}
summaryError.value = "个人学习信息没有获取到。";
if (!hadData) summaryState.value = "error";
return;
}
summary.value = payload;
const parsed = asSummary(payload);
if (!parsed) {
summaryError.value = "数据异常";
if (!hadData) summaryState.value = "error";
return;
}
summary.value = parsed;
avatarBroken.value = false;
summaryError.value = "";
summaryState.value = "ready";
} catch {
if (!hadData) {
summaryError.value = "个人学习信息没有获取到。";
summaryState.value = "error";
}
summaryError.value = "个人学习信息没有获取到。";
if (!hadData) summaryState.value = "error";
} finally {
busy = false;
}
@@ -318,11 +357,11 @@ async function saveSchedule() {
day == null || hour == null || minute == null || second == null
|| !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)
) {
scheduleError.value = "请填写完整的定时启动时间";
scheduleError.value = "请填写完整的开始时刻";
return;
}
if (workers == null || !Number.isInteger(workers) || workers < 1 || workers > 8) {
scheduleError.value = "线程数量须为 1 到 8";
scheduleError.value = "同时学习课程数须为 1 到 8";
return;
}
scheduleSaving.value = true;
@@ -330,7 +369,7 @@ async function saveSchedule() {
try {
await putJson("/api/settings/monthly-target", { monthly_target: target }, "没有保存每月目标。");
await putJson("/api/settings/study-start", { day, hour, minute, second, enabled: scheduleEnabled.value }, "没有保存定时启动。");
await putJson("/api/settings/course-workers", { workers }, "没有保存线程数量。");
await putJson("/api/settings/course-workers", { workers }, "没有保存同时学习课程数。");
await loadStudyControl();
} catch (exc) {
scheduleError.value = exc instanceof Error ? exc.message : "没有保存。";
@@ -375,6 +414,8 @@ function restoreProxy() {
proxyHasPassword.value = savedProxy.hasPassword;
proxyError.value = "";
}
const proxyAccountProps = { autocomplete: "off", name: "proxy-account" };
const proxyPasswordProps = { autocomplete: "new-password", name: "proxy-password" };
const proxyOptions = [
{ label: "关闭", value: "off" },
{ label: "自动", value: "pool" },
@@ -618,7 +659,12 @@ watch(proxyOpen, (open, wasOpen) => {
if (wasOpen && !open) restoreProxy();
});
let lastWake = 0;
function studyWake() {
const now = Date.now();
if (now - lastWake < 800) return;
lastWake = now;
if (studyClosed) return;
void loadStudyControl();
if (!studySocket || studySocket.readyState === WebSocket.CLOSING || studySocket.readyState === WebSocket.CLOSED) {
@@ -694,24 +740,22 @@ onUnmounted(() => {
<section class="panel-card home-summary" :aria-busy="summaryState === 'loading'">
<div class="home-top">
<div class="home-top-main">
<n-alert v-if="summaryState === 'error'" class="summary-error" type="error">{{ summaryError }}</n-alert>
<div v-else class="profile">
<template v-if="summary">
<img v-if="summary.avatar" class="avatar" :src="summary.avatar" alt="" referrerpolicy="no-referrer" />
<div v-else class="brand-mark avatar-fallback" aria-hidden="true">{{ summary.name.slice(0, 1) || "E" }}</div>
<div>
<strong>{{ summary.name || props.employeeId }}</strong>
<span>{{ summary.department }}<template v-if="summary.level"> · {{ summary.level }}</template></span>
</div>
</template>
<template v-else>
<div class="bone bone-avatar"></div>
<div class="bone-copy">
<div class="bone bone-name"></div>
<div class="bone bone-meta"></div>
</div>
<div class="spin" role="status" aria-label="正在获取"></div>
</template>
<n-alert v-if="summaryError" class="summary-error" type="error">{{ summaryError }}</n-alert>
<div v-if="summary" class="profile">
<img v-if="summary.avatar && !avatarBroken" class="avatar" :src="summary.avatar" alt="" referrerpolicy="no-referrer" @error="avatarBroken = true" />
<div v-else class="brand-mark avatar-fallback" aria-hidden="true">{{ (summary.name || props.employeeId).slice(0, 1) || "E" }}</div>
<div>
<strong>{{ summary.name || props.employeeId }}</strong>
<span>{{ summary.department }}<template v-if="summary.level"> · {{ summary.level }}</template></span>
</div>
</div>
<div v-else-if="summaryState === 'loading'" class="profile">
<div class="bone bone-avatar"></div>
<div class="bone-copy">
<div class="bone bone-name"></div>
<div class="bone bone-meta"></div>
</div>
<div class="spin" role="status" aria-label="正在获取"></div>
</div>
</div>
<n-tooltip placement="bottom">
@@ -750,11 +794,10 @@ onUnmounted(() => {
<n-alert v-if="scheduleError" class="summary-error" type="error">{{ scheduleError }}</n-alert>
<div class="study-card-body">
<div class="study-config">
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="132" :show-feedback="false" size="small">
<n-form-item v-if="targetLoaded" label="每月目标">
<div class="target-control">
<n-input-number
id="monthly-target"
v-model:value="monthlyTarget"
button-placement="both"
:min="0"
@@ -765,17 +808,19 @@ onUnmounted(() => {
<span class="target-unit">分钟</span>
</div>
</n-form-item>
<n-form-item v-if="startLoaded" label="定时开启">
<n-form-item v-if="startLoaded" label="定时启动">
<n-switch v-model:value="scheduleEnabled" size="small" />
</n-form-item>
<n-form-item v-if="startLoaded" label="定时启动">
<n-form-item v-if="startLoaded" label="开始时刻">
<div class="start-control">
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
<n-select v-model:value="startDay" size="small" :options="dayOptions" class="day-select" :disabled="!scheduleEnabled" />
<n-tooltip v-if="scheduleEnabled && startDay === 1" placement="top">
<template #trigger>
<n-icon class="day-warn"><WarningOutline /></n-icon>
<button type="button" class="hint-icon day-warn" aria-label="开始时刻说明">
<n-icon><WarningOutline /></n-icon>
</button>
</template>
不推荐使用
公共代理不稳定,学习可能中断
</n-tooltip>
<n-time-picker
class="start-time"
@@ -787,18 +832,8 @@ onUnmounted(() => {
/>
</div>
</n-form-item>
<n-form-item v-if="workersLoaded" label="线程数量">
<div class="target-control">
<n-select id="course-workers" class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
<n-tooltip v-if="courseWorkers === 1" placement="top">
<template #trigger>
<button type="button" class="hint-icon" aria-label="说明">
<n-icon><HelpCircleOutline /></n-icon>
</button>
</template>
{{ workerHint }}
</n-tooltip>
</div>
<n-form-item v-if="workersLoaded" label="同时学习课程数">
<n-select class="worker-select" v-model:value="courseWorkers" size="small" :options="workerOptions" />
</n-form-item>
</n-form>
<div class="study-actions">
@@ -832,12 +867,13 @@ onUnmounted(() => {
<div class="study-live-status">
<span
class="study-indicator"
role="status"
:class="{
active: !studyFailed && (studyControl.started || studyControl.active),
down: studyFailed,
}"
></span>
<span class="study-text" :class="{ muted: !studyControl.started && !studyControl.active }">{{ studyLabel }}</span>
<span class="study-text" aria-live="polite" :class="{ muted: !studyControl.started && !studyControl.active }">{{ studyLabel }}</span>
</div>
<div v-if="targetLoaded" class="study-progress">
<div class="study-progress-meta">
@@ -855,7 +891,7 @@ onUnmounted(() => {
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
<span class="study-worker-count">{{ workerCount(row) }}</span>
<span v-if="showHeartbeat(row)" class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
<span class="study-dot" :class="row.ok ? 'up' : 'down'" :aria-label="row.ok ? '正常' : '异常'"></span>
<span class="study-dot" role="status" :class="row.ok ? 'up' : 'down'" :aria-label="row.ok ? '正常' : '异常'"></span>
</li>
</ul>
<p v-else-if="studyHint" class="study-live-hint">{{ studyHint }}</p>
@@ -883,7 +919,7 @@ onUnmounted(() => {
<n-input-number v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" placeholder="请输入" />
</n-form-item>
<n-form-item label="账号">
<n-input v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" />
<n-input v-model:value="proxyUser" size="small" placeholder="可不填" :input-props="proxyAccountProps" />
</n-form-item>
<n-form-item label="密码">
<n-input
@@ -892,7 +928,7 @@ onUnmounted(() => {
type="password"
show-password-on="click"
:placeholder="proxyHasPassword ? '已保存,留空则保持' : '可不填'"
autocomplete="new-password"
:input-props="proxyPasswordProps"
/>
</n-form-item>
</template>