feat: 后台课程清单管理和自动同步

This commit is contained in:
2026-11-15 00:48:03 +08:00
parent 9f44082c8a
commit 98c11f42d8
7 changed files with 669 additions and 6 deletions
+239
View File
@@ -0,0 +1,239 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NInput, NPagination } from "naive-ui";
interface CourseRow {
title: string;
kind: string;
url: string;
contributor: string;
learners: string;
released_on: string;
updated_on: string;
comments: string;
}
interface KindOption {
name: string;
value: string;
count: number;
}
const loading = ref(true);
const errorText = ref("");
const query = ref("");
const appliedQuery = ref("");
const kind = ref("");
const kinds = ref<KindOption[]>([]);
const items = ref<CourseRow[]>([]);
const total = ref(0);
const syncedAt = ref<string | null>(null);
const page = ref(1);
const pageSize = ref(50);
const pageSizes = [20, 50, 100];
const kindTotal = computed(() => kinds.value.reduce((sum, item) => sum + item.count, 0));
const fetching = ref(false);
let poll = 0;
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function textOf(value: unknown) {
return typeof value === "string" ? value : "";
}
function asCourse(value: unknown): CourseRow | null {
if (!isRecord(value) || typeof value.title !== "string") return null;
return {
title: value.title,
kind: textOf(value.kind),
url: textOf(value.url),
contributor: textOf(value.contributor),
learners: textOf(value.learners),
released_on: textOf(value.released_on),
updated_on: textOf(value.updated_on),
comments: textOf(value.comments),
};
}
function formatTime(value: string | null) {
if (!value) return "";
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())}`;
}
async function load() {
loading.value = items.value.length === 0;
errorText.value = "";
try {
const params = new URLSearchParams({
q: appliedQuery.value,
kind: kind.value,
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/courses?${params}`);
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = isRecord(payload) && typeof payload.detail === "string" ? payload.detail : "课程清单没有获取到。";
return;
}
if (!isRecord(payload) || !Array.isArray(payload.items)) {
errorText.value = "课程清单没有获取到。";
return;
}
items.value = payload.items.map(asCourse).filter((item): item is CourseRow => item !== null);
total.value = typeof payload.total === "number" ? payload.total : items.value.length;
syncedAt.value = typeof payload.synced_at === "string" ? payload.synced_at : null;
kinds.value = Array.isArray(payload.kinds) ? payload.kinds.flatMap(asKind) : [];
fetching.value = payload.running === true;
if (typeof payload.message === "string" && payload.message) errorText.value = payload.message;
if (fetching.value) startPoll();
else stopPoll();
} catch {
errorText.value = "课程清单没有获取到。";
} finally {
loading.value = false;
}
}
function startPoll() {
if (poll) return;
poll = window.setInterval(() => void load(), 3000);
}
function stopPoll() {
window.clearInterval(poll);
poll = 0;
}
async function loadCourses() {
errorText.value = "";
fetching.value = true;
try {
const response = await fetch("/api/admin/courses/load", { method: "POST" });
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
errorText.value = isRecord(payload) && typeof payload.detail === "string" ? payload.detail : "课程清单没有获取到。";
return;
}
startPoll();
} catch {
fetching.value = false;
errorText.value = "课程清单没有获取到。";
}
}
function asKind(value: unknown): KindOption[] {
if (!isRecord(value) || typeof value.name !== "string" || typeof value.count !== "number") return [];
return [{ name: value.name, value: textOf(value.value), count: value.count }];
}
function pickKind(value: string) {
kind.value = value;
page.value = 1;
void load();
}
function goPage(next: number) {
page.value = next;
void load();
}
function changeSize(size: number) {
pageSize.value = size;
page.value = 1;
void load();
}
function search() {
appliedQuery.value = query.value.trim();
page.value = 1;
void load();
}
onMounted(() => {
void load();
});
onUnmounted(() => stopPoll());
</script>
<template>
<section class="page admin-page">
<header class="page-head">
<div>
<h2>课程清单</h2>
<p v-if="!loading && !errorText">
{{ total }} 门<template v-if="syncedAt"> · 更新于 {{ formatTime(syncedAt) }}</template>
</p>
</div>
<form class="course-search" @submit.prevent="search">
<n-button attr-type="button" :loading="fetching" :disabled="fetching" @click="loadCourses">加载课程列表</n-button>
<n-input v-model:value="query" placeholder="名称或贡献者" clearable @clear="search" />
<n-button attr-type="submit">搜索</n-button>
</form>
</header>
<div v-if="kinds.length" class="course-kinds">
<button type="button" class="kind-chip" :class="{ active: kind === '' }" @click="pickKind('')">全部<span>{{ kindTotal }}</span></button>
<button
v-for="item in kinds"
:key="item.value || item.name"
type="button"
class="kind-chip"
:class="{ active: kind === item.value }"
@click="pickKind(item.value)"
>
{{ item.name }}<span>{{ item.count }}</span>
</button>
</div>
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
<div class="admin-scroll">
<p v-if="loading" class="admin-status">正在获取</p>
<p v-else-if="fetching && !items.length" class="admin-status">正在获取</p>
<p v-else-if="!items.length" class="admin-status">还没有课程</p>
<table v-else class="admin-table">
<thead>
<tr>
<th>名称</th>
<th>类型</th>
<th>地址</th>
<th>贡献者</th>
<th>学习人数</th>
<th>发布</th>
<th>更新</th>
</tr>
</thead>
<tbody>
<tr v-for="row in items" :key="`${row.title}-${row.updated_on}`">
<td>{{ row.title }}</td>
<td>{{ row.kind }}</td>
<td class="course-url"><a v-if="row.url" :href="row.url" target="_blank" rel="noreferrer">{{ row.url }}</a></td>
<td>{{ row.contributor }}</td>
<td class="when">{{ row.learners }}</td>
<td class="when">{{ row.released_on }}</td>
<td class="when">{{ row.updated_on }}</td>
</tr>
</tbody>
</table>
</div>
<n-pagination
v-if="total > 0"
class="course-pager"
:page="page"
:page-size="pageSize"
:item-count="total"
:page-sizes="pageSizes"
show-size-picker
show-quick-jumper
@update:page="goPage"
@update:page-size="changeSize"
>
<template #prefix>共 {{ total }} 条</template>
</n-pagination>
</section>
</template>
+31 -4
View File
@@ -5,22 +5,48 @@ import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons
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 SettingsView from "../features/admin/SettingsView.vue";
defineProps<{ username: string }>();
const emit = defineEmits<{ logout: []; refresh: [] }>();
const page = ref<AdminPageKey>("users");
const page = ref<AdminPageKey>(pageFromHash());
const collapsed = ref(window.innerWidth < 800);
function pageFromHash(): AdminPageKey {
const name = window.location.hash.replace(/^#\/?/, "");
if (name === "courses" || name === "settings" || name === "users") return name;
return "users";
}
function remember(next: AdminPageKey) {
const hash = `#/${next}`;
if (window.location.hash !== hash) history.replaceState(null, "", hash);
}
function onHashChange() {
page.value = pageFromHash();
}
function onResize() {
if (window.innerWidth < 800) collapsed.value = true;
}
onMounted(() => window.addEventListener("resize", onResize));
onUnmounted(() => window.removeEventListener("resize", onResize));
onMounted(() => {
remember(page.value);
window.addEventListener("resize", onResize);
window.addEventListener("hashchange", onHashChange);
});
onUnmounted(() => {
window.removeEventListener("resize", onResize);
window.removeEventListener("hashchange", onHashChange);
});
function onMenu(key: string) {
if (key === "users" || key === "settings") page.value = key;
if (key === "users" || key === "courses" || key === "settings") {
page.value = key;
remember(key);
}
}
</script>
@@ -78,6 +104,7 @@ function onMenu(key: string) {
</n-layout-sider>
<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'" />
<SettingsView v-else-if="page === 'settings'" @saved="emit('refresh')" />
</n-layout>
</n-layout>
+3 -2
View File
@@ -1,15 +1,16 @@
import type { Component } from "vue";
import { h } from "vue";
import { NIcon } from "naive-ui";
import { PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
import { LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
function renderIcon(icon: Component) {
return () => h(NIcon, null, { default: () => h(icon) });
}
export type AdminPageKey = "users" | "settings";
export type AdminPageKey = "users" | "courses" | "settings";
export const adminNavOptions = [
{ label: "用户管理", key: "users" as const, icon: renderIcon(PeopleOutline) },
{ label: "课程清单", key: "courses" as const, icon: renderIcon(LibraryOutline) },
{ label: "系统配置", key: "settings" as const, icon: renderIcon(SettingsOutline) },
];