feat: 增加公告栏并让用户自选学时判断

This commit is contained in:
Nixevol
2026-11-19 04:08:30 +08:00
parent 3fe6d4c111
commit 4d4fe224bc
20 changed files with 789 additions and 64 deletions
+196
View File
@@ -0,0 +1,196 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NAlert, NButton, NDatePicker, NForm, NFormItem, NInput, NModal, useDialog } from "naive-ui";
import { isRecord, textOf } from "../../shared/text";
interface Notice {
id: number;
title: string;
body: string;
link_url: string;
published_at: string;
}
const dialog = useDialog();
const loading = ref(true);
const errorText = ref("");
const items = ref<Notice[]>([]);
const editorOpen = ref(false);
const saving = ref(false);
const editorError = ref("");
const editingId = ref<number | null>(null);
const title = ref("");
const body = ref("");
const linkUrl = ref("");
const publishedAt = ref<number | null>(Date.now());
function minuteText(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const pad = (part: number) => String(part).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function asNotice(value: unknown): Notice | null {
if (!isRecord(value) || typeof value.id !== "number") return null;
return {
id: value.id,
title: textOf(value.title),
body: textOf(value.body),
link_url: textOf(value.link_url),
published_at: textOf(value.published_at),
};
}
async function load() {
loading.value = true;
try {
const response = await apiFetch("/api/admin/notices");
const payload: unknown = await response.json().catch(() => []);
if (!response.ok || !Array.isArray(payload)) {
errorText.value = "公告没有获取到。";
return;
}
errorText.value = "";
items.value = payload.map(asNotice).filter((item): item is Notice => item !== null);
} catch {
errorText.value = "公告没有获取到。";
} finally {
loading.value = false;
}
}
function openCreate() {
editingId.value = null;
title.value = "";
body.value = "";
linkUrl.value = "";
publishedAt.value = Date.now();
editorError.value = "";
editorOpen.value = true;
}
function openEdit(row: Notice) {
editingId.value = row.id;
title.value = row.title;
body.value = row.body;
linkUrl.value = row.link_url;
const stamp = new Date(row.published_at).getTime();
publishedAt.value = Number.isNaN(stamp) ? Date.now() : stamp;
editorError.value = "";
editorOpen.value = true;
}
async function save() {
if (saving.value) return;
if (!title.value.trim() || !body.value.trim() || publishedAt.value == null) {
editorError.value = "请填写标题、正文和发布时间。";
return;
}
saving.value = true;
editorError.value = "";
const payload = {
title: title.value.trim(),
body: body.value.trim(),
link_url: linkUrl.value.trim(),
published_at: new Date(publishedAt.value).toISOString(),
};
try {
const path = editingId.value == null ? "/api/admin/notices" : `/api/admin/notices/${editingId.value}`;
const response = await apiFetch(path, {
method: editingId.value == null ? "POST" : "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
editorError.value = "没有保存。";
return;
}
editorOpen.value = false;
await load();
} catch {
editorError.value = "没有保存。";
} finally {
saving.value = false;
}
}
function remove(row: Notice) {
dialog.warning({
title: "删除公告",
content: `删除「${row.title}」?`,
positiveText: "删除",
negativeText: "取消",
onPositiveClick: async () => {
const response = await apiFetch(`/api/admin/notices/${row.id}`, { method: "DELETE" });
if (!response.ok) {
errorText.value = "没有删除。";
return;
}
await load();
},
});
}
onMounted(load);
</script>
<template>
<section class="page list-page">
<header class="page-head">
<div>
<h2>公告</h2>
<p v-if="!loading">共 {{ items.length }} 条</p>
</div>
<n-button type="primary" @click="openCreate">发布公告</n-button>
</header>
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
<p v-if="loading" class="admin-status">正在获取</p>
<p v-else-if="!items.length" class="admin-status">还没有公告</p>
<ol v-else class="notice-admin">
<li v-for="item in items" :key="item.id">
<div>
<time>{{ minuteText(item.published_at) }}</time>
<strong>{{ item.title }}</strong>
<p>{{ item.body }}</p>
<a v-if="item.link_url" :href="item.link_url" target="_blank" rel="noreferrer">{{ item.link_url }}</a>
</div>
<div class="notice-admin-actions">
<n-button size="small" quaternary @click="openEdit(item)">编辑</n-button>
<n-button size="small" quaternary type="error" @click="remove(item)">删除</n-button>
</div>
</li>
</ol>
<n-modal
:show="editorOpen"
preset="card"
:title="editingId == null ? '发布公告' : '编辑公告'"
:style="{ width: 'min(640px, calc(100vw - 32px))' }"
:content-style="{ maxHeight: 'min(70vh, 640px)', overflow: 'auto' }"
@update:show="(show) => (editorOpen = show)"
>
<n-alert v-if="editorError" class="summary-error" type="error">{{ editorError }}</n-alert>
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="88" :show-feedback="false">
<n-form-item label="标题">
<n-input v-model:value="title" maxlength="80" placeholder="一句话说明" />
</n-form-item>
<n-form-item label="正文">
<n-input v-model:value="body" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }" maxlength="4000" placeholder="公告内容" />
</n-form-item>
<n-form-item label="链接">
<n-input v-model:value="linkUrl" placeholder="可不填,须以 http 或 https 开头" />
</n-form-item>
<n-form-item label="发布时间">
<n-date-picker v-model:value="publishedAt" type="datetime" format="yyyy-MM-dd HH:mm" :time-picker-props="{ format: 'HH:mm' }" />
</n-form-item>
</n-form>
<template #footer>
<div class="modal-actions">
<n-button @click="editorOpen = false">取消</n-button>
<n-button type="primary" :loading="saving" @click="save">保存</n-button>
</div>
</template>
</n-modal>
</section>
</template>
+3 -3
View File
@@ -217,12 +217,12 @@ async function save() {
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="176" :show-feedback="false" size="small" @submit.prevent="save">
<n-form-item label="判断依据">
<n-radio-group v-model:value="hoursSource" size="small">
<n-radio-button value="api">接口本月学时</n-radio-button>
<n-radio-button value="history">学时历史统计</n-radio-button>
<n-radio-button value="api">官方统计数据</n-radio-button>
<n-radio-button value="history">历史统计数据</n-radio-button>
</n-radio-group>
</n-form-item>
</n-form>
<p class="form-hint">首页、学时历史和达标判断使用同一来源</p>
<p class="form-hint">新用户默认使用这里的选择,已有用户不受影响</p>
</n-collapse-item>
<n-collapse-item title="管理员" name="admin">
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="176" :show-feedback="false" size="small" @submit.prevent="save">
+20 -6
View File
@@ -3,6 +3,7 @@ import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInputNumber, NModal, NProgress, NRadioButton, NRadioGroup, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
import NoticeRail from "./NoticeRail.vue";
import HoursCompare from "../../shared/HoursCompare.vue";
import ProxyFields from "../../shared/ProxyFields.vue";
import { STUDY_DAY_DEFAULT, STUDY_DAY_MAX, STUDY_DAY_MIN, dayOptions, workerOptions } from "../../shared/studyFields";
@@ -161,8 +162,6 @@ function withMinutes(value: string) {
return `${value} 分钟`;
}
const historyHoursNote = "由于Euniv学时统计缺陷/统计延后,本系统已开启采用当月学习历史统计本月学时,可能会导致本系统中显示的本月学时与Euniv官方网站不一样。";
interface HourFact {
label: string;
value: string;
@@ -399,6 +398,7 @@ async function loadStart() {
const workersLoaded = ref(false);
const courseWorkers = ref<number | null>(1);
const heartbeatLoaded = ref(false);
const hoursSource = ref<"api" | "history">("api");
const heartbeatMode = ref("auto");
const heartbeatVideo = ref<number | null>(30);
const heartbeatDocument = ref<number | null>(120);
@@ -487,6 +487,7 @@ function scheduleBody(): Record<string, unknown> | null {
heartbeat_video_seconds: heartbeatVideo.value ?? 30,
heartbeat_document_seconds: heartbeatDocument.value ?? 120,
heartbeat_scorm_seconds: heartbeatScorm.value ?? 120,
hours_source: hoursSource.value,
};
}
@@ -498,6 +499,7 @@ async function saveSchedule() {
try {
await putJson("/api/settings/study", body, "没有保存定时配置。");
await loadStudyControl();
refresh();
} catch (exc) {
scheduleError.value = exc instanceof Error ? exc.message : "没有保存。";
} finally {
@@ -578,6 +580,7 @@ async function loadHeartbeat() {
heartbeatVideo.value = typeof data.heartbeat_video_seconds === "number" ? data.heartbeat_video_seconds : 30;
heartbeatDocument.value = typeof data.heartbeat_document_seconds === "number" ? data.heartbeat_document_seconds : 120;
heartbeatScorm.value = typeof data.heartbeat_scorm_seconds === "number" ? data.heartbeat_scorm_seconds : 120;
hoursSource.value = data.hours_source === "history" ? "history" : "api";
heartbeatLoaded.value = true;
return true;
} catch {
@@ -1028,7 +1031,6 @@ onUnmounted(() => {
刷新数据
</n-tooltip>
</div>
<p v-if="summary?.hours_source === 'history'" class="hours-source-note">{{ historyHoursNote }}</p>
<dl class="facts">
<div v-for="item in facts" :key="item.label">
<dt>{{ item.label }}</dt>
@@ -1044,6 +1046,7 @@ onUnmounted(() => {
<p v-if="summary?.limited" class="study-live-hint">只统计了最近 50 页</p>
</section>
<div class="home-lower">
<section class="panel-card study-card" :class="{ 'is-busy': studyingWorkers.length > 0 }">
<header class="study-head">
<h3>自动学习</h3>
@@ -1135,10 +1138,19 @@ onUnmounted(() => {
</label>
</div>
</n-form-item>
<n-form-item v-if="heartbeatLoaded" label="学时判断">
<n-radio-group v-model:value="hoursSource" size="small">
<n-radio-button value="api">官方统计数据</n-radio-button>
<n-radio-button value="history">历史统计数据</n-radio-button>
</n-radio-group>
</n-form-item>
</n-form>
<p v-if="heartbeatLoaded && heartbeatMode === 'manual'" class="study-config-hint">
间隔越短,发送越频繁。设为 0 时连续发送,课程列表不显示倒计时。
</p>
<p v-if="heartbeatLoaded" class="study-config-hint">
{{ hoursSource === "history" ? "根据学习历史统计本月学时" : "根据官方接口返回进行判断(官方统计可能会延后,导致学时可能会多刷)" }}
</p>
<div class="study-actions">
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
<template #icon><n-icon><GlobeOutline /></n-icon></template>
@@ -1175,7 +1187,7 @@ onUnmounted(() => {
</div>
<n-progress type="line" :percentage="monthProgress.pct" :show-indicator="false" :height="6" />
</div>
<div v-if="studyingWorkers.length" class="study-courses" :class="{ 'no-countdown': !countdownOn }">
<div class="study-courses" :class="{ 'no-countdown': !countdownOn }">
<div class="study-course-head" aria-hidden="true">
<span>正在学习</span>
<span></span>
@@ -1184,7 +1196,7 @@ onUnmounted(() => {
<span v-if="countdownOn" class="num">下次心跳</span>
<span></span>
</div>
<ul class="study-workers" aria-label="正在学习的课程">
<ul v-if="studyingWorkers.length" class="study-workers" aria-label="正在学习的课程">
<li v-for="row in studyingWorkers" :key="row.id" class="study-worker">
<span class="study-worker-title" :title="workerTitle(row)">{{ workerTitle(row) }}</span>
<div class="study-worker-bar">
@@ -1196,11 +1208,13 @@ onUnmounted(() => {
<span class="study-dot" role="img" :class="row.ok ? 'up' : 'down'" :aria-label="row.ok ? '正常' : '异常'"></span>
</li>
</ul>
<p v-else-if="studyHint" class="study-live-hint">{{ studyHint }}</p>
</div>
<p v-else-if="studyHint" class="study-live-hint">{{ studyHint }}</p>
</div>
</div>
</section>
<NoticeRail />
</div>
</div>
<n-modal
:show="proxyOpen"
+76
View File
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NIcon } from "naive-ui";
import { ChevronBackOutline, ChevronForwardOutline, MegaphoneOutline } from "@vicons/ionicons5";
interface Notice {
id: number;
title: string;
body: string;
link_url: string;
published_at: string;
}
const STORAGE_KEY = "euniv-notice-collapsed";
const collapsed = ref(localStorage.getItem(STORAGE_KEY) === "1");
const items = ref<Notice[]>([]);
function minuteText(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const pad = (part: number) => String(part).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function toggle() {
collapsed.value = !collapsed.value;
localStorage.setItem(STORAGE_KEY, collapsed.value ? "1" : "0");
}
onMounted(async () => {
try {
const response = await apiFetch("/api/announcements");
const payload: unknown = await response.json().catch(() => []);
if (!response.ok || !Array.isArray(payload)) return;
items.value = payload.flatMap((item) => {
if (!item || typeof item !== "object") return [];
const row = item as Record<string, unknown>;
if (typeof row.id !== "number" || typeof row.title !== "string") return [];
return [{
id: row.id,
title: row.title,
body: typeof row.body === "string" ? row.body : "",
link_url: typeof row.link_url === "string" ? row.link_url : "",
published_at: typeof row.published_at === "string" ? row.published_at : "",
}];
});
} catch {
items.value = [];
}
});
</script>
<template>
<aside class="notice-rail" :class="{ collapsed }">
<header class="notice-head">
<button type="button" class="notice-toggle" :aria-label="collapsed ? '展开公告' : '收起公告'" @click="toggle">
<n-icon><ChevronForwardOutline v-if="!collapsed" /><ChevronBackOutline v-else /></n-icon>
</button>
<h3 v-if="!collapsed">公告</h3>
<n-icon v-else class="notice-mark"><MegaphoneOutline /></n-icon>
<span v-if="collapsed && items.length" class="notice-count">{{ items.length }}</span>
</header>
<div v-if="!collapsed" class="notice-scroll">
<p v-if="!items.length" class="notice-empty">暂无公告</p>
<ol v-else class="notice-timeline">
<li v-for="item in items" :key="item.id">
<time>{{ minuteText(item.published_at) }}</time>
<strong>{{ item.title }}</strong>
<p>{{ item.body }}</p>
<a v-if="item.link_url" :href="item.link_url" target="_blank" rel="noreferrer">打开链接</a>
</li>
</ol>
</div>
</aside>
</template>
+5 -3
View File
@@ -6,6 +6,7 @@ import { isDark, toggleTheme } from "../shared/theme";
import { adminNavOptions, type AdminPageKey } from "./adminNavigation";
import UsersView from "../features/admin/UsersView.vue";
import CoursesView from "../features/admin/CoursesView.vue";
import NoticesView from "../features/admin/NoticesView.vue";
import SettingsView from "../features/admin/SettingsView.vue";
defineProps<{ username: string }>();
@@ -13,7 +14,7 @@ const emit = defineEmits<{ logout: []; refresh: [] }>();
const page = ref<AdminPageKey>(pageFromHash());
const collapsed = ref(window.innerWidth < 800);
const holdOpen = ref(false);
const pages = new Set<AdminPageKey>(["users", "courses", "settings"]);
const pages = new Set<AdminPageKey>(["users", "courses", "notices", "settings"]);
function hashName() {
return window.location.hash.replace(/^#\/?/, "");
@@ -21,7 +22,7 @@ function hashName() {
function pageFromHash(): AdminPageKey {
const name = hashName();
if (name === "courses" || name === "settings" || name === "users") return name;
if (name === "courses" || name === "settings" || name === "users" || name === "notices") return name;
return "users";
}
@@ -72,7 +73,7 @@ onUnmounted(() => {
});
function onMenu(key: string) {
if (key === "users" || key === "courses" || key === "settings") show(key);
if (key === "users" || key === "courses" || key === "notices" || key === "settings") show(key);
}
</script>
@@ -131,6 +132,7 @@ function onMenu(key: string) {
<n-layout class="content" :native-scrollbar="false" content-style="height: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column;">
<UsersView v-if="page === 'users'" />
<CoursesView v-else-if="page === 'courses'" />
<NoticesView v-else-if="page === 'notices'" />
<SettingsView v-else-if="page === 'settings'" @saved="emit('refresh')" />
</n-layout>
</n-layout>
+3 -2
View File
@@ -1,16 +1,17 @@
import type { Component } from "vue";
import { h } from "vue";
import { NIcon } from "naive-ui";
import { LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
import { LibraryOutline, MegaphoneOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
function renderIcon(icon: Component) {
return () => h(NIcon, null, { default: () => h(icon) });
}
export type AdminPageKey = "users" | "courses" | "settings";
export type AdminPageKey = "users" | "courses" | "notices" | "settings";
export const adminNavOptions = [
{ label: "用户管理", key: "users" as const, icon: renderIcon(PeopleOutline) },
{ label: "课程清单", key: "courses" as const, icon: renderIcon(LibraryOutline) },
{ label: "公告", key: "notices" as const, icon: renderIcon(MegaphoneOutline) },
{ label: "系统配置", key: "settings" as const, icon: renderIcon(SettingsOutline) },
];
+203 -21
View File
@@ -469,14 +469,21 @@ select {
.home {
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
overflow: hidden;
display: flex;
flex-direction: column;
gap: 16px;
padding-bottom: 8px;
}
.home-lower {
flex: 1;
min-height: 0;
display: flex;
gap: 16px;
align-items: stretch;
}
.panel-card {
background: var(--panel);
border: 1px solid var(--line);
@@ -573,7 +580,6 @@ select {
}
.home-summary {
position: relative;
flex: none;
display: flex;
flex-direction: column;
@@ -599,20 +605,6 @@ select {
flex: 0 1 auto;
}
.hours-source-note {
position: absolute;
z-index: 1;
top: 16px;
left: 240px;
right: 52px;
margin: 0;
color: #f5a524;
font-size: 12px;
line-height: 1.55;
text-align: center;
pointer-events: none;
}
.home-refresh.n-button {
flex: none;
color: var(--muted);
@@ -796,8 +788,10 @@ select {
.study-card,
.study-card.is-busy {
flex: 0 0 auto;
overflow: visible;
flex: 1 1 auto;
min-width: 0;
min-height: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 12px;
@@ -829,6 +823,7 @@ select {
.study-live {
min-width: 0;
min-height: calc(48px + 20px + 28px + 8 * 32px);
display: flex;
flex-direction: column;
gap: 20px;
@@ -869,9 +864,11 @@ select {
.study-courses {
--course-cols: minmax(7rem, 1.4fr) minmax(4rem, 1fr) 56px 88px 56px 8px;
height: calc(28px + 8 * 32px);
overflow: hidden;
display: flex;
flex-direction: column;
gap: 10px;
gap: 0;
}
.study-courses.no-countdown {
@@ -888,6 +885,8 @@ select {
}
.study-course-head {
box-sizing: border-box;
height: 28px;
padding-bottom: 8px;
border-bottom: 1px solid var(--line);
font-size: 12px;
@@ -901,11 +900,18 @@ select {
.study-workers {
list-style: none;
flex: 1;
min-height: 0;
margin: 0;
padding: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
gap: 0;
}
.study-worker {
min-height: 32px;
}
.study-worker-title {
@@ -1373,11 +1379,27 @@ select {
}
@media (max-width: 1100px), (max-height: 760px) {
.home-lower {
flex-direction: column;
overflow: auto;
}
.study-card,
.study-card.is-busy {
flex: none;
overflow: visible;
}
.notice-rail,
.notice-rail.collapsed {
flex: none;
width: 100%;
height: 240px;
}
.notice-rail.collapsed {
height: 44px;
}
}
@media (max-width: 1100px) {
@@ -1831,3 +1853,163 @@ body .n-base-select-menu .n-base-select-option__content {
flex-wrap: wrap;
}
}
.notice-rail {
flex: 0 0 280px;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 4px;
overflow: hidden;
}
.notice-rail.collapsed {
flex-basis: 44px;
align-items: center;
padding: 8px 0;
}
.notice-head {
display: flex;
align-items: center;
gap: 8px;
min-height: 28px;
}
.notice-rail.collapsed .notice-head {
flex-direction: column;
}
.notice-head h3 {
margin: 0;
font-size: 13px;
font-weight: 650;
}
.notice-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--text);
cursor: pointer;
}
.notice-mark {
font-size: 16px;
}
.notice-count {
min-width: 18px;
padding: 0 4px;
border-radius: 9px;
background: #f5a524;
color: #1b1b1b;
font-size: 11px;
line-height: 18px;
text-align: center;
}
.notice-scroll {
flex: 1;
min-height: 0;
overflow: auto;
}
.notice-empty {
margin: 8px 0 0;
color: var(--muted);
font-size: 13px;
}
.notice-timeline {
list-style: none;
margin: 0;
padding: 0 0 0 14px;
border-left: 1px solid var(--line);
}
.notice-timeline li {
position: relative;
display: flex;
flex-direction: column;
gap: 4px;
margin: 0 0 16px;
padding-left: 12px;
}
.notice-timeline li::before {
content: "";
position: absolute;
left: -18px;
top: 6px;
width: 7px;
height: 7px;
border-radius: 50%;
background: #f5a524;
}
.notice-timeline time {
color: var(--muted);
font-size: 12px;
}
.notice-timeline strong {
font-size: 13px;
}
.notice-timeline p {
margin: 0;
white-space: pre-wrap;
font-size: 13px;
line-height: 1.5;
}
.notice-timeline a {
color: var(--text);
font-size: 12px;
}
.notice-admin {
list-style: none;
flex: 1;
min-height: 0;
margin: 0;
padding: 0;
overflow: auto;
}
.notice-admin li {
display: flex;
justify-content: space-between;
gap: 16px;
padding: 12px 0;
border-bottom: 1px solid var(--line);
}
.notice-admin time {
display: block;
color: var(--muted);
font-size: 12px;
}
.notice-admin p {
margin: 6px 0 0;
white-space: pre-wrap;
}
.notice-admin-actions {
display: flex;
gap: 4px;
flex: none;
}