feat: 后台课程清单管理和自动同步
This commit is contained in:
@@ -10,6 +10,7 @@ from admin.identity import identity
|
||||
from admin.session import admin_session_active, clear_admin_session
|
||||
from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view
|
||||
from admin.users import check_all, check_employee, delete_user, list_users, read_credentials, set_paused
|
||||
from euniv.courses import course_page, request_course_sync_now
|
||||
from euniv.db import get_db
|
||||
|
||||
public_router = APIRouter()
|
||||
@@ -60,6 +61,30 @@ def admin_logout(response: Response) -> dict:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@admin_router.post("/courses/load")
|
||||
def post_courses_load(_: str = Depends(require_admin)) -> dict:
|
||||
state = request_course_sync_now()
|
||||
if state == "empty":
|
||||
raise HTTPException(status_code=400, detail="没有可用的登录凭证")
|
||||
if state == "disabled":
|
||||
raise HTTPException(status_code=400, detail="课程清单没有获取到。")
|
||||
return {"running": state in {"start", "busy"}}
|
||||
|
||||
|
||||
@admin_router.get("/courses")
|
||||
def get_courses(
|
||||
q: str = "",
|
||||
kind: str = "",
|
||||
offset: int = 0,
|
||||
limit: int = 50,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict:
|
||||
bounded = min(max(limit, 1), 100)
|
||||
start = max(offset, 0)
|
||||
return course_page(db, q, start, bounded, kind)
|
||||
|
||||
|
||||
@admin_router.get("/users")
|
||||
def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]:
|
||||
return list_users(db)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""课程清单和同步记录。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0005_courses"
|
||||
down_revision = "0004_admin_settings"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"courses",
|
||||
sa.Column("path", sa.String(length=160), primary_key=True),
|
||||
sa.Column("title", sa.String(length=300), nullable=False, server_default=""),
|
||||
sa.Column("kind", sa.String(length=32), nullable=False, server_default=""),
|
||||
sa.Column("contributor", sa.String(length=64), nullable=False, server_default=""),
|
||||
sa.Column("recommend", sa.String(length=16), nullable=False, server_default=""),
|
||||
sa.Column("learners", sa.String(length=16), nullable=False, server_default=""),
|
||||
sa.Column("released_on", sa.String(length=16), nullable=False, server_default=""),
|
||||
sa.Column("updated_on", sa.String(length=16), nullable=False, server_default=""),
|
||||
sa.Column("comments", sa.String(length=16), nullable=False, server_default=""),
|
||||
)
|
||||
op.create_table(
|
||||
"course_sync",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("last_employee_id", sa.String(length=32), nullable=False, server_default=""),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("next_allowed_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("course_count", sa.Integer(), nullable=False, server_default="0"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("course_sync")
|
||||
op.drop_table("courses")
|
||||
@@ -0,0 +1,230 @@
|
||||
"""后台课程清单。一次只跑一个全量任务,完成后随机隔 8 到 16 小时。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import random
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EUNIV
|
||||
from euniv.models import Account, Course, CourseSync
|
||||
|
||||
_lock = threading.Lock()
|
||||
_running = False
|
||||
_message = ""
|
||||
|
||||
|
||||
def sync_decision(
|
||||
running: bool,
|
||||
next_allowed_at: datetime | None,
|
||||
now: datetime,
|
||||
force: bool = False,
|
||||
) -> str:
|
||||
if running:
|
||||
return "busy"
|
||||
if not force and next_allowed_at is not None and now < _as_utc(next_allowed_at):
|
||||
return "wait"
|
||||
return "start"
|
||||
|
||||
|
||||
def next_gap(rng: random.Random | None = None) -> timedelta:
|
||||
hours = (rng or random).uniform(8, 16)
|
||||
return timedelta(hours=hours)
|
||||
|
||||
|
||||
def choose_account(rows: list[tuple[str, bool | None]], trigger: str, last: str) -> str | None:
|
||||
eligible = [employee_id for employee_id, valid in rows if employee_id == trigger or valid is not False]
|
||||
if not eligible:
|
||||
return None
|
||||
if len(eligible) > 1 and last in eligible:
|
||||
eligible = [employee_id for employee_id in eligible if employee_id != last]
|
||||
eligible.sort()
|
||||
later = [employee_id for employee_id in eligible if last and employee_id > last]
|
||||
return later[0] if later else eligible[0]
|
||||
|
||||
|
||||
def request_course_sync(employee_id: str) -> bool:
|
||||
"""凭据刚被确认有效时尝试启动。已有任务或未到间隔则直接放弃。"""
|
||||
return _begin(employee_id, force=False) == "start"
|
||||
|
||||
|
||||
def request_course_sync_now() -> str:
|
||||
"""手动加载。任务已在跑则放弃;否则立刻开始,成功后重新计算间隔。"""
|
||||
return _begin("", force=True)
|
||||
|
||||
|
||||
def course_running() -> bool:
|
||||
return _running
|
||||
|
||||
|
||||
def course_message() -> str:
|
||||
return _message
|
||||
|
||||
|
||||
def course_page(db: Session, query: str, offset: int, limit: int, kind: str = "") -> dict:
|
||||
text = query.strip()
|
||||
base = []
|
||||
if text:
|
||||
like = f"%{text}%"
|
||||
base.append(or_(Course.title.like(like), Course.contributor.like(like)))
|
||||
counts = db.execute(select(Course.kind, func.count()).where(*base).group_by(Course.kind)).all()
|
||||
kinds = [
|
||||
{"name": name or "未分类", "value": name, "count": int(count)}
|
||||
for name, count in sorted(counts, key=lambda row: (_kind_rank(row[0]), row[0]))
|
||||
]
|
||||
filters = list(base)
|
||||
if kind:
|
||||
filters.append(Course.kind == kind)
|
||||
total = db.scalar(select(func.count()).select_from(Course).where(*filters)) or 0
|
||||
rows = db.scalars(
|
||||
select(Course)
|
||||
.where(*filters)
|
||||
.order_by(Course.updated_on.desc(), Course.title)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
).all()
|
||||
sync = db.get(CourseSync, 1)
|
||||
return {
|
||||
"total": int(total),
|
||||
"synced_at": _iso(sync.finished_at) if sync else None,
|
||||
"running": course_running(),
|
||||
"message": course_message(),
|
||||
"kinds": kinds,
|
||||
"items": [
|
||||
{
|
||||
"title": row.title,
|
||||
"kind": row.kind,
|
||||
"url": EUNIV + row.path,
|
||||
"contributor": row.contributor,
|
||||
"recommend": row.recommend,
|
||||
"learners": row.learners,
|
||||
"released_on": row.released_on,
|
||||
"updated_on": row.updated_on,
|
||||
"comments": row.comments,
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
_KIND_RANK = ("课程包", "课程", "视频", "音频", "文档", "微课", "压缩包")
|
||||
|
||||
|
||||
def _kind_rank(name: str) -> tuple[int, str]:
|
||||
try:
|
||||
return (_KIND_RANK.index(name), name)
|
||||
except ValueError:
|
||||
return (len(_KIND_RANK), name)
|
||||
|
||||
|
||||
def _begin(employee_id: str, force: bool) -> str:
|
||||
if os.environ.get("EUNIV_DISABLE_REFRESH") == "1":
|
||||
return "disabled"
|
||||
global _running
|
||||
with _lock:
|
||||
decision = sync_decision(_running, _next_allowed(), datetime.now(timezone.utc), force=force)
|
||||
if decision != "start":
|
||||
return decision
|
||||
if not _has_credential(employee_id):
|
||||
return "empty"
|
||||
_running = True
|
||||
threading.Thread(target=_run, args=(employee_id,), name="euniv-course-sync", daemon=True).start()
|
||||
return "start"
|
||||
|
||||
|
||||
def _has_credential(trigger: str) -> bool:
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
with SessionLocal() as db:
|
||||
return _pick_employee(db, trigger) is not None
|
||||
|
||||
|
||||
def _run(trigger: str) -> None:
|
||||
global _running, _message
|
||||
try:
|
||||
stored = _fetch_and_store(trigger)
|
||||
with _lock:
|
||||
_message = "" if stored else "课程清单没有获取到。"
|
||||
except Exception:
|
||||
with _lock:
|
||||
_message = "课程清单没有获取到。"
|
||||
finally:
|
||||
with _lock:
|
||||
_running = False
|
||||
|
||||
|
||||
def _fetch_and_store(trigger: str) -> bool:
|
||||
from euniv.client import EunivClient
|
||||
from euniv.crypto import decrypt_secret
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
import json
|
||||
|
||||
with SessionLocal() as db:
|
||||
employee_id = _pick_employee(db, trigger)
|
||||
if not employee_id:
|
||||
return False
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None or not account.credential_cipher:
|
||||
return False
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
client = EunivClient(employee_id, password)
|
||||
try:
|
||||
client.restore(credential)
|
||||
if not client.credential_alive():
|
||||
return False
|
||||
courses = client.list_courses()
|
||||
finally:
|
||||
client.close()
|
||||
if not courses:
|
||||
return False
|
||||
with SessionLocal() as db:
|
||||
db.execute(delete(Course))
|
||||
db.add_all(Course(**course) for course in courses)
|
||||
sync = db.get(CourseSync, 1)
|
||||
if sync is None:
|
||||
sync = CourseSync(id=1)
|
||||
db.add(sync)
|
||||
sync.last_employee_id = employee_id
|
||||
sync.finished_at = datetime.now(timezone.utc)
|
||||
sync.next_allowed_at = sync.finished_at + next_gap()
|
||||
sync.course_count = len(courses)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def _pick_employee(db: Session, trigger: str) -> str | None:
|
||||
rows = db.execute(
|
||||
select(Account.employee_id, Account.credential_valid)
|
||||
.where(Account.credential_cipher != "")
|
||||
.order_by(Account.employee_id)
|
||||
).all()
|
||||
sync = db.get(CourseSync, 1)
|
||||
last = sync.last_employee_id if sync else ""
|
||||
return choose_account([(row.employee_id, row.credential_valid) for row in rows], trigger, last)
|
||||
|
||||
|
||||
def _next_allowed() -> datetime | None:
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
with SessionLocal() as db:
|
||||
sync = db.get(CourseSync, 1)
|
||||
return sync.next_allowed_at if sync else None
|
||||
|
||||
|
||||
def _as_utc(value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
moment = _as_utc(value)
|
||||
return moment.isoformat()
|
||||
@@ -0,0 +1,104 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from euniv.client import parse_course_page
|
||||
from euniv.courses import choose_account, next_gap, sync_decision
|
||||
|
||||
|
||||
def test_parse_course_page_reads_a_catalog_row() -> None:
|
||||
page = """
|
||||
<div class="summary"><span>共1187条 每页</span></div>
|
||||
<tr>
|
||||
<td>
|
||||
<span class="Knowledge_CoursePackage"> </span>
|
||||
<a href="/kng/view/package/a43b7806df7142daa6889104e28b3a38.html" class="link4" target="_blank" title='【日常运维】-告警监控与分析'>【日常运维】-告警监控与分析</a>
|
||||
</td>
|
||||
<td>
|
||||
<a class="link4" title='王小伟' target="_blank" href="/myhome.htm?userID=6831ecc3-1afc-4c3f-8f49-c291ce9bd014"> 王小伟</a>
|
||||
</td>
|
||||
<td class="textcenter"><span class="color5">0</span></td>
|
||||
<td class="textcenter"><span class="color5">1513</span><span class="hide_readcount" style="display:none">6890</span></td>
|
||||
<td class="textcenter"><span class="color5">2026-10-16</span></td>
|
||||
<td class="textcenter"><span class="color5">2026-10-16</span></td>
|
||||
<td class="textleft"><label>(5)</label></td>
|
||||
</tr>
|
||||
"""
|
||||
parsed = parse_course_page(page)
|
||||
assert parsed["total"] == 1187
|
||||
assert parsed["courses"] == [{
|
||||
"path": "/kng/view/package/a43b7806df7142daa6889104e28b3a38.html",
|
||||
"title": "【日常运维】-告警监控与分析",
|
||||
"kind": "课程包",
|
||||
"contributor": "王小伟",
|
||||
"recommend": "0",
|
||||
"learners": "1513",
|
||||
"released_on": "2026-10-16",
|
||||
"updated_on": "2026-10-16",
|
||||
"comments": "5",
|
||||
}]
|
||||
|
||||
|
||||
def test_course_sync_skips_when_busy_or_too_soon() -> None:
|
||||
now = datetime(2026, 11, 13, tzinfo=timezone.utc)
|
||||
assert sync_decision(True, None, now) == "busy"
|
||||
assert sync_decision(False, now + timedelta(hours=1), now) == "wait"
|
||||
assert sync_decision(False, now - timedelta(seconds=1), now) == "start"
|
||||
assert sync_decision(False, None, now) == "start"
|
||||
assert sync_decision(False, now + timedelta(hours=3), now, force=True) == "start"
|
||||
assert sync_decision(True, None, now, force=True) == "busy"
|
||||
|
||||
|
||||
def test_course_sync_rotates_accounts() -> None:
|
||||
rows = [("1001", True), ("1002", True), ("1003", False)]
|
||||
assert choose_account(rows, "1001", "1001") == "1002"
|
||||
assert choose_account(rows, "1002", "1002") == "1001"
|
||||
assert choose_account([("1001", True)], "1001", "1001") == "1001"
|
||||
assert choose_account([("1003", False)], "1001", "") is None
|
||||
|
||||
|
||||
class _FixedRandom:
|
||||
def uniform(self, start: float, end: float) -> float:
|
||||
assert (start, end) == (8, 16)
|
||||
return 12
|
||||
|
||||
|
||||
def test_course_page_filters_by_title() -> None:
|
||||
from euniv.courses import course_page
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import Course
|
||||
|
||||
with SessionLocal() as db:
|
||||
db.add(Course(
|
||||
path="/kng/view/package/a.html",
|
||||
title="融合课程",
|
||||
kind="课程包",
|
||||
contributor="王",
|
||||
recommend="1",
|
||||
learners="2",
|
||||
released_on="2026-01-01",
|
||||
updated_on="2026-02-01",
|
||||
comments="3",
|
||||
))
|
||||
db.add(Course(
|
||||
path="/kng/view/document/b.html",
|
||||
title="另一门",
|
||||
kind="文档",
|
||||
contributor="李",
|
||||
recommend="0",
|
||||
learners="1",
|
||||
released_on="2026-01-02",
|
||||
updated_on="2026-03-01",
|
||||
comments="0",
|
||||
))
|
||||
db.commit()
|
||||
page = course_page(db, "融合", 0, 50)
|
||||
assert page["total"] == 1
|
||||
assert page["items"][0]["title"] == "融合课程"
|
||||
assert [item["name"] for item in page["kinds"]] == ["课程包"]
|
||||
filtered = course_page(db, "", 0, 50, kind="文档")
|
||||
assert filtered["total"] == 1
|
||||
assert filtered["items"][0]["kind"] == "文档"
|
||||
assert {item["name"] for item in filtered["kinds"]} == {"课程包", "文档"}
|
||||
|
||||
|
||||
def test_course_gap_stays_between_eight_and_sixteen_hours() -> None:
|
||||
assert next_gap(_FixedRandom()) == timedelta(hours=12)
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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) },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user