feat: 首页拆分独立加载、骨架动画和手动刷新

This commit is contained in:
2026-11-15 00:48:26 +08:00
parent 9a6f134f56
commit fa6811dab7
9 changed files with 657 additions and 282 deletions
+27
View File
@@ -20,6 +20,9 @@ from euniv.models import Account
from euniv.service import (
fetch_exam_detail,
fetch_home,
fetch_home_exams,
fetch_home_summary,
fetch_home_trainings,
fetch_training_detail,
login_and_store,
revoke_credential,
@@ -151,6 +154,30 @@ def home(request: Request, db: Session = Depends(get_db)) -> dict:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/summary")
def home_summary(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_summary(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/exams")
def home_exams(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_exams(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/trainings")
def home_trainings(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home_trainings(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/exam")
def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
+171 -13
View File
@@ -6,6 +6,7 @@ import base64
import io
import random
import re
import threading
import time
import uuid
from datetime import datetime
@@ -72,6 +73,38 @@ def training_form(page: str) -> dict[str, str]:
return found
_authorize_guard = threading.Lock()
_authorize_locks: dict[str, threading.Lock] = {}
def _authorize_lock(account_id: str) -> threading.Lock:
with _authorize_guard:
lock = _authorize_locks.get(account_id)
if lock is None:
lock = threading.RLock()
_authorize_locks[account_id] = lock
return lock
_SITE_SHARE_SECONDS = 90
_site_sessions: dict[str, tuple[float, list[tuple[str, str, str, str]]]] = {}
def _remember_site(account_id: str, client: httpx.Client) -> None:
jar = getattr(getattr(client, "cookies", None), "jar", None)
if not account_id or jar is None:
return
dumped = []
for cookie in jar:
dumped.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
_site_sessions[account_id] = (time.time(), dumped)
def _load_cookies(client: httpx.Client, dumped: list[tuple[str, str, str, str]]) -> None:
for name, value, domain, path in dumped:
client.cookies.set(name, value, domain=domain, path=path)
def _by_closeness(items: list[dict], key: str) -> list[dict]:
ordered = sorted(items, key=lambda item: item.get(key, float("inf")))
for item in ordered:
@@ -231,6 +264,64 @@ def _plain(value: str) -> str:
return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace(" ", " ").strip()
_COURSE_KIND = {
"Knowledge_CoursePackage": "课程包",
"Knowledge_Course": "课程",
"Knowledge_Scorm": "课程",
"Knowledge_Video": "视频",
"Knowledge_Audio": "音频",
"Knowledge_Word": "文档",
"Knowledge_PPT": "文档",
"Knowledge_PDF": "文档",
"Knowledge_Excel": "文档",
"Knowledge_SourceCode": "压缩包",
"Knowledge_XuanYes": "微课",
}
def parse_course_page(page: str) -> dict:
total_match = re.search(r"共(\d+)条", page)
courses = []
for row in re.findall(r"<tr>\s*<td>[\s\S]*?</tr>", page):
link = re.search(r'href="(/(?:kng/view|knowledge)/[^"]+)"[^>]*title=\'([^\']*)\'', row)
if not link:
continue
kind = re.search(r'class="(Knowledge_[A-Za-z]+)"', row)
contributor = re.search(r"title='([^']*)'[^>]*href=\"/myhome\.htm", row)
numbers = re.findall(r'<td class="textcenter"\s*>\s*<span class="color5">([^<]*)</span>', row)
comments = re.search(r"<label>\((\d+)\)</label>", row)
courses.append({
"path": link.group(1),
"title": link.group(2).strip(),
"kind": _course_kind(kind.group(1) if kind else "", link.group(1)),
"contributor": contributor.group(1).strip() if contributor else "",
"recommend": numbers[0].strip() if len(numbers) > 0 else "",
"learners": numbers[1].strip() if len(numbers) > 1 else "",
"released_on": numbers[2].strip() if len(numbers) > 2 else "",
"updated_on": numbers[3].strip() if len(numbers) > 3 else "",
"comments": comments.group(1) if comments else "",
})
return {
"courses": courses,
"total": int(total_match.group(1)) if total_match else None,
}
def _course_kind(class_name: str, path: str) -> str:
named = _COURSE_KIND.get(class_name)
if named:
return named
if "/package/" in path:
return "课程包"
if "/scorm/" in path:
return "课程"
if "/video/" in path or "/audio/" in path:
return "视频" if "/video/" in path else "音频"
if "/document/" in path:
return "文档"
return ""
def _leading_number(value: str) -> float:
match = re.search(r"(\d+)", value)
return float(match.group(1)) if match else float("inf")
@@ -600,8 +691,8 @@ class EunivClient:
"class_count": class_count,
}
def home_snapshot(self) -> dict:
"""实时读取首页要展示的个人信息,调用方不得把结果写入数据库。"""
def home_summary(self) -> dict:
"""实时读取首页上半部分。调用方不得把结果写入数据库。"""
info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
info = info_resp.json()
if not isinstance(info, dict) or "cnName" not in info:
@@ -622,6 +713,8 @@ class EunivClient:
today = today_resp.json()
periods = self._period_minutes()
if not periods["year"] and not periods["month"]:
raise RuntimeError("个人学习信息没有获取到。")
return {
"name": info.get("cnName") or "",
"avatar": info.get("headPictureUrl") or "",
@@ -633,10 +726,24 @@ class EunivClient:
"total_hours": score.get("actualStudyHour") or "",
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
"points": "" if score.get("ablePoint") is None else score.get("ablePoint"),
"trainings": _by_closeness(self.online_trainings(), "sort_days"),
"exams": _by_closeness(self.my_exams(), "sort_at"),
}
def home_exams(self) -> list[dict]:
return _by_closeness(self.my_exams(), "sort_at")
def home_trainings(self) -> list[dict]:
return _by_closeness(self.online_trainings(), "sort_days")
def home_snapshot(self) -> dict:
"""实时读取整页首页。调用方不得把结果写入数据库。"""
data = self.home_summary()
data["trainings"] = self.home_trainings()
data["exams"] = self.home_exams()
return data
def month_hours(self) -> str:
return self._period_minutes().get("month", "")
def _period_minutes(self) -> dict[str, str]:
text = self._study_period_page()
found = {}
@@ -645,18 +752,36 @@ class EunivClient:
found[key] = match.group(1) if match else ""
return found
def _ensure_site(self) -> None:
def _ensure_site(self) -> str:
"""确认网页会话可用。同一账号短时间内复用已打开的会话,避免并行请求各自重新登录。"""
account_id = str(self._profile.get("accountId") or "")
if self._profile.get("token") and not getattr(self, "_site_ready", False):
probe = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
if "spMonthlyPeriod" not in probe.text:
self.authorize(self._profile)
self._site_ready = True
with _authorize_lock(account_id):
if getattr(self, "_site_ready", False):
return ""
shared = _site_sessions.get(account_id)
if shared and time.time() - shared[0] < _SITE_SHARE_SECONDS:
_load_cookies(self.client, shared[1])
self._site_ready = True
return ""
probe = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
if "spMonthlyPeriod" not in probe.text:
self.authorize(self._profile)
self._site_ready = True
_remember_site(account_id, self.client)
return ""
self._site_ready = True
_remember_site(account_id, self.client)
return probe.text
return ""
def _study_period_page(self) -> str:
self._ensure_site()
cached = self._ensure_site()
if "spMonthlyPeriod" in cached:
return cached
response = self.client.get(
f"{EUNIV}/study/myperiod.htm",
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
@@ -668,12 +793,16 @@ class EunivClient:
url = f"{EUNIV}/sty/mystudytask.htm"
headers = {"User-Agent": USER_AGENT, "Referer": url, "Origin": EUNIV}
html = self.client.get(url, headers=headers).text
if "scType" not in html and "el-plan-li-3" not in html:
raise RuntimeError("培训列表没有获取到。")
items = parse_training_cards(html, "进行中")
form = training_form(html)
for event, status in (("2,已完成", "已完成"), ("1,已归档", "已归档")):
form["__EVENTTARGET"] = "scType"
form["__EVENTARGUMENT"] = event
html = self.client.post(url, data=form, headers=headers).text
if "scType" not in html and "el-plan-li-3" not in html:
raise RuntimeError("培训列表没有获取到。")
items.extend(parse_training_cards(html, status))
form = training_form(html)
return items
@@ -687,8 +816,37 @@ class EunivClient:
form["__EVENTTARGET"] = "scExamState"
form["__EVENTARGUMENT"] = ""
html = self.client.post(url, data=form, headers=headers).text
if "scExamState" not in html and 'name="userExam"' not in html:
raise RuntimeError("考试列表没有获取到。")
return self._pages(url, headers, html, parse_exam_cards, "start")
def list_courses(self) -> list[dict]:
self._ensure_site()
found: dict[str, dict] = {}
total = None
page = 1
while page <= 120:
html = self._site_page(
"/kng/knowledgecatalogsearch.htm"
f"?sf=RecommendLevel&s=dc&st=1&mode=null&ps=50&pi={page}"
)
parsed = parse_course_page(html)
if total is None:
total = parsed["total"]
if not parsed["courses"]:
break
before = len(found)
for course in parsed["courses"]:
found[course["path"]] = course
if total is not None and len(found) >= total:
break
if len(found) == before:
break
page += 1
if total is not None and len(found) < total:
raise RuntimeError("课程清单没有取全")
return list(found.values())
def exam_detail(self, path: str) -> dict:
if not _exam_detail_path(path):
raise RuntimeError("考试明细无法打开")
+59 -3
View File
@@ -17,6 +17,17 @@ from euniv.models import Account
_PENDING_SECONDS = 180
_pending: dict[str, "PendingLogin"] = {}
_credential_guard = threading.Lock()
_credential_locks: dict[str, threading.Lock] = {}
def _credential_lock(employee_id: str) -> threading.Lock:
with _credential_guard:
lock = _credential_locks.get(employee_id)
if lock is None:
lock = threading.Lock()
_credential_locks[employee_id] = lock
return lock
@dataclass
@@ -69,6 +80,7 @@ def login_and_store(
account = db.get(Account, employee_id)
if account and account.password_cipher and account.credential_cipher:
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory):
_request_course_sync(employee_id)
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = client_factory(employee_id, password)
@@ -82,6 +94,7 @@ def login_and_store(
held = True
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
_persist(db, employee_id, password, client, profile)
_request_course_sync(employee_id)
return {"employee_id": employee_id}
finally:
if not held:
@@ -116,6 +129,7 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
_pending.pop(attempt_id, None)
try:
_persist(db, pending.employee_id, pending.password, pending.client, profile)
_request_course_sync(pending.employee_id)
return {"employee_id": pending.employee_id}
finally:
pending.client.close()
@@ -126,6 +140,18 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
return _live(db, employee_id, client_factory, lambda client: client.home_snapshot())
def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.home_summary())
def fetch_home_exams(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"exams": _live(db, employee_id, client_factory, lambda client: client.home_exams())}
def fetch_home_trainings(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
return {"trainings": _live(db, employee_id, client_factory, lambda client: client.home_trainings())}
def fetch_exam_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict:
return _live(db, employee_id, client_factory, lambda client: client.exam_detail(path))
@@ -164,9 +190,13 @@ def _live(db: Session, employee_id: str, client_factory, read):
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
updated = client.export_credential()
if _dump(updated) != _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
with _credential_lock(employee_id):
db.refresh(account)
current_raw = account.credential_cipher
current = json.loads(decrypt_secret(current_raw)) if current_raw else {}
if _dump(updated) != _dump(current) and _dump(current) == _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
finally:
client.close()
@@ -202,6 +232,8 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
return
client = None
valid = False
checked_alive = False
hours = ""
try:
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
@@ -212,10 +244,13 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
checked_alive = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
if valid:
hours = _month_hours(client)
except Exception:
db.rollback()
valid = False
@@ -229,7 +264,11 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
except Exception:
pass
record_outcome(account, valid)
if hours:
account.month_hours = hours
db.commit()
if checked_alive:
_request_course_sync(employee_id)
class _RefreshGate:
@@ -301,5 +340,22 @@ def start_credential_refresh() -> _RefreshGate:
return gate
def _month_hours(client) -> str:
reader = getattr(client, "month_hours", None)
if reader is None:
return ""
try:
value = reader()
except Exception:
return ""
return value if isinstance(value, str) else ""
def _request_course_sync(employee_id: str) -> None:
from euniv.courses import request_course_sync
request_course_sync(employee_id)
def stored_password(account: Account) -> str:
return decrypt_secret(account.password_cipher)
+2
View File
@@ -24,6 +24,8 @@ def fresh_database():
connection.execute(text("DROP TABLE IF EXISTS accounts"))
connection.execute(text("DROP TABLE IF EXISTS schedules"))
connection.execute(text("DROP TABLE IF EXISTS system_config"))
connection.execute(text("DROP TABLE IF EXISTS courses"))
connection.execute(text("DROP TABLE IF EXISTS course_sync"))
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
init_db()
ensure_admin_seed()
+9
View File
@@ -96,6 +96,9 @@ def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
assert COOKIE_NAME not in client.cookies
assert client.get("/api/session").json() == {"role": "admin", "username": "admin"}
assert client.get("/api/home").status_code == 403
assert client.get("/api/home/summary").status_code == 403
assert client.get("/api/home/exams").status_code == 403
assert client.get("/api/home/trainings").status_code == 403
assert client.get("/api/exam", params={"path": "/exam/x"}).status_code == 403
assert client.get("/api/training", params={"path": "/plan/x"}).status_code == 403
assert calls == []
@@ -302,6 +305,9 @@ class _Alive:
def credential_alive(self) -> bool:
return True
def month_hours(self) -> str:
return "660"
def export_credential(self) -> dict:
return dict(CREDENTIAL)
@@ -355,6 +361,7 @@ def test_refresh_records_outcome_and_skips_paused_accounts() -> None:
empty = db.get(Account, "empty-user")
assert alive is not None and failed is not None and paused is not None and empty is not None
assert alive.credential_valid is True
assert alive.month_hours == "660"
assert alive.last_refresh_at is not None
assert decrypt_secret(alive.password_cipher) == "secret-pass"
assert json.loads(decrypt_secret(alive.credential_cipher))["yxt_token"] == "yxt-1"
@@ -436,10 +443,12 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
"refresh_paused",
"last_refresh_at",
"credential_valid",
"month_hours",
}
assert saved["has_credential"] is True
assert saved["refresh_paused"] is False
assert saved["credential_valid"] is True
assert saved["month_hours"] == ""
assert isinstance(saved["last_refresh_at"], str)
calls.clear()
again = client.get("/api/admin/users")
+63
View File
@@ -1,5 +1,6 @@
import json
import pytest
from fastapi.testclient import TestClient
from euniv.client import JigsawRejected, ManualJigsaw
@@ -108,6 +109,7 @@ def test_login_stores_password_and_credential_only() -> None:
"refresh_paused",
"last_refresh_at",
"credential_valid",
"month_hours",
}
home = client.get("/api/home")
@@ -390,3 +392,64 @@ def test_exam_and_training_details() -> None:
"score": "0/5.2",
"hours": "52/52",
}
def test_home_sections_are_separate() -> None:
import euniv.api as api_module
import euniv.service as service_module
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
)
api_module.fetch_home_summary = lambda db, employee_id: {"name": "分段"}
api_module.fetch_home_exams = lambda db, employee_id: {"exams": [{"name": "一门考试"}]}
api_module.fetch_home_trainings = lambda db, employee_id: {"trainings": [{"name": "一门培训"}]}
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert response.status_code == 200
assert client.get("/api/home/summary").json()["name"] == "分段"
assert client.get("/api/home/exams").json()["exams"] == [{"name": "一门考试"}]
assert client.get("/api/home/trainings").json()["trainings"] == [{"name": "一门培训"}]
def test_period_page_is_not_fetched_twice() -> None:
from euniv.client import EunivClient
client = EunivClient.__new__(EunivClient)
client._profile = {"token": "t", "accountId": "a"}
client._site_ready = False
calls: list[str] = []
class Response:
text = '<span id="spAnnualPeriod" title="34分钟"></span><span id="spMonthlyPeriod" title="12分钟"></span>'
class HTTP:
def get(self, url: str, headers=None):
calls.append(url)
return Response()
client.client = HTTP()
assert client._period_minutes() == {"year": "34", "month": "12"}
assert len(calls) == 1
def test_exam_list_rejects_unrecognized_page() -> None:
from euniv.client import EunivClient
client = EunivClient.__new__(EunivClient)
client._profile = {"token": "t", "accountId": "a"}
client._site_ready = True
class Response:
text = "<html>login</html>"
class HTTP:
def get(self, url: str, headers=None):
return Response()
def post(self, url: str, data=None, headers=None):
return Response()
client.client = HTTP()
with pytest.raises(RuntimeError, match="考试列表没有获取到"):
client.my_exams()
+91 -252
View File
@@ -1,72 +1,9 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NModal } from "naive-ui";
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
interface ExamItem {
name: string;
status: string;
result: string;
start: string;
detail: string;
}
interface TrainingItem {
name: string;
status: string;
progress: number;
assigned: string;
credits: string;
detail: string;
}
interface ExamAttempt {
submitted: string;
score: string;
result: string;
}
interface ExamDetail {
total_score: string;
pass_score: string;
questions: string;
window: string;
times: string;
limit: string;
examinee: string;
view_policy: string;
notice: string;
attempts: ExamAttempt[];
}
interface TrainingTask {
name: string;
progress: string;
score: string;
hours: string;
}
interface TrainingPhase {
name: string;
hours: string;
credits: string;
tasks: TrainingTask[];
}
interface TrainingDetail {
owner: string;
earned_hours: string;
actual_hours: string;
reward_hours: string;
earned_credits: string;
actual_credits: string;
reward_credits: string;
rank: string;
progress: string;
deadline: string;
phases: TrainingPhase[];
}
interface HomeProfile {
interface HomeSummary {
name: string;
avatar: string;
department: string;
@@ -77,24 +14,17 @@ interface HomeProfile {
total_hours: string;
total_score: string;
points: string | number | null;
exams: ExamItem[];
trainings: TrainingItem[];
}
type SectionState = "loading" | "ready" | "error";
const props = defineProps<{ employeeId: string }>();
const profile = ref<HomeProfile | null>(null);
const errorText = ref("");
const loading = ref(false);
const dialogOpen = ref(false);
const dialogTitle = ref("");
const dialogKind = ref<"exam" | "training">("exam");
const examDetail = ref<ExamDetail | null>(null);
const trainingDetail = ref<TrainingDetail | null>(null);
const detailError = ref("");
const detailLoading = ref(false);
let timer = 0;
let requestId = 0;
let detailRequest = 0;
const summary = ref<HomeSummary | null>(null);
const summaryState = ref<SectionState>("loading");
const summaryError = ref("");
const refreshing = ref(false);
let refreshRunning = false;
let busy = false;
function amount(value: string | number | null | undefined) {
if (value === null || value === undefined || value === "") return "—";
@@ -105,206 +35,115 @@ function amount(value: string | number | null | undefined) {
}
const facts = computed(() => {
const current = profile.value;
if (!current) return [];
const current = summary.value;
return [
{ label: "本年学时", value: amount(current.year_hours) },
{ label: "本月学时", value: amount(current.month_hours) },
{ label: "今日学时", value: amount(current.today_hours) },
{ label: "累计学时", value: amount(current.total_hours) },
{ label: "累计学分", value: amount(current.total_score) },
{ label: "可用积分", value: amount(current.points) },
{ 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 ? amount(current.total_score) : "" },
{ label: "可用积分", value: current ? amount(current.points) : "" },
];
});
function trainingMeta(item: TrainingItem) {
const parts = [item.status, `${item.progress}%`];
if (item.credits) parts.push(`${item.credits} 学分`);
return parts.join(" · ");
function failureText(payload: { detail?: unknown }, fallback: string) {
return typeof payload.detail === "string" ? payload.detail : fallback;
}
async function openDetail(kind: "exam" | "training", item: { name: string; detail: string }) {
const current = ++detailRequest;
dialogKind.value = kind;
dialogTitle.value = item.name;
examDetail.value = null;
trainingDetail.value = null;
detailError.value = "";
dialogOpen.value = true;
if (!item.detail) {
detailError.value = "明细没有获取到。";
detailLoading.value = false;
return;
}
detailLoading.value = true;
async function loadSummary() {
if (busy) return;
busy = true;
const hadData = summary.value !== null;
if (!hadData) summaryState.value = "loading";
try {
const route = kind === "exam" ? "/api/exam" : "/api/training";
const response = await fetch(`${route}?${new URLSearchParams({ path: item.detail })}`);
const response = await fetch("/api/home/summary");
const payload = await response.json().catch(() => ({}));
if (current !== detailRequest) return;
if (!response.ok) {
detailError.value = typeof payload.detail === "string" ? payload.detail : "明细没有获取到。";
if (!hadData) {
summaryError.value = failureText(payload, "个人学习信息没有获取到。");
summaryState.value = "error";
}
return;
}
if (kind === "exam") examDetail.value = payload;
else trainingDetail.value = payload;
summary.value = payload;
summaryError.value = "";
summaryState.value = "ready";
} catch {
if (current === detailRequest) detailError.value = "明细没有获取到。";
} finally {
if (current === detailRequest) detailLoading.value = false;
}
}
async function load() {
const current = ++requestId;
loading.value = profile.value === null;
try {
const response = await fetch("/api/home");
const payload = await response.json().catch(() => ({}));
if (current !== requestId) return;
if (!response.ok) {
errorText.value = typeof payload.detail === "string" ? payload.detail : "首页信息没有获取到。";
return;
if (!hadData) {
summaryError.value = "个人学习信息没有获取到。";
summaryState.value = "error";
}
errorText.value = "";
profile.value = payload;
} catch {
if (current === requestId) errorText.value = "首页信息没有获取到。";
} finally {
if (current === requestId) loading.value = false;
busy = false;
}
}
onMounted(() => {
void load();
timer = window.setInterval(() => void load(), 30000);
});
function refresh() {
if (refreshRunning) return;
refreshRunning = true;
refreshing.value = true;
void loadSummary().finally(() => {
refreshRunning = false;
refreshing.value = false;
});
}
onUnmounted(() => window.clearInterval(timer));
onMounted(refresh);
</script>
<template>
<section class="page home-page">
<header class="page-head">
<h2>首页</h2>
</header>
<n-alert v-if="errorText && !profile" type="error">{{ errorText }}</n-alert>
<p v-else-if="loading" class="home-status">正在获取</p>
<div v-if="profile" class="home">
<n-alert v-if="errorText" type="error">{{ errorText }}</n-alert>
<div class="home-summary">
<div class="profile">
<img v-if="profile.avatar" class="avatar" :src="profile.avatar" alt="" referrerpolicy="no-referrer" />
<div v-else class="brand-mark avatar-fallback" aria-hidden="true">{{ profile.name.slice(0, 1) || "E" }}</div>
<div>
<strong>{{ profile.name || props.employeeId }}</strong>
<span>{{ profile.department }}<template v-if="profile.level"> · {{ profile.level }}</template></span>
<div class="home">
<div class="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>
</div>
</div>
<n-tooltip placement="bottom">
<template #trigger>
<n-button
class="home-refresh"
quaternary
circle
size="small"
aria-label="刷新数据"
:loading="refreshing"
@click="refresh"
>
<template #icon><n-icon><RefreshOutline /></n-icon></template>
</n-button>
</template>
刷新数据
</n-tooltip>
</div>
<dl class="facts">
<div v-for="item in facts" :key="item.label">
<dt>{{ item.label }}</dt>
<dd>{{ item.value }}</dd>
<dd>
<span v-if="summaryState === 'loading'" class="bone bone-value"></span>
<template v-else>{{ item.value || "—" }}</template>
</dd>
</div>
</dl>
</div>
<div class="boards">
<section class="board" aria-labelledby="exam-heading">
<h3 id="exam-heading">我的考试</h3>
<div class="rail" tabindex="0">
<p v-if="!(profile.exams || []).length" class="rail-empty">没有考试</p>
<ol v-else>
<li v-for="item in profile.exams" :key="`${item.start}-${item.name}`" class="event">
<span class="mark" aria-hidden="true"></span>
<button type="button" class="event-hit" @click="openDetail('exam', item)">
<time :datetime="item.start">{{ item.start }}</time>
<strong>{{ item.name }}</strong>
<p class="meta">
<span>{{ item.status }}</span>
<span v-if="item.result" :class="item.result === '已通过' ? 'ok' : 'late'">{{ item.result }}</span>
</p>
</button>
</li>
</ol>
</div>
</section>
<section class="board" aria-labelledby="training-heading">
<h3 id="training-heading">线上培训</h3>
<div class="rail" tabindex="0">
<p v-if="!(profile.trainings || []).length" class="rail-empty">没有线上培训</p>
<ol v-else>
<li v-for="item in profile.trainings" :key="`${item.assigned}-${item.name}`" class="event">
<span class="mark" aria-hidden="true"></span>
<button type="button" class="event-hit" @click="openDetail('training', item)">
<time>{{ item.assigned }}</time>
<strong>{{ item.name }}</strong>
<p class="meta"><span>{{ trainingMeta(item) }}</span></p>
</button>
</li>
</ol>
</div>
</section>
</div>
</div>
<n-modal
v-model:show="dialogOpen"
preset="card"
:title="dialogTitle"
:style="{ width: 'min(760px, calc(100vw - 32px))' }"
:content-style="{ maxHeight: '70vh', overflow: 'auto' }"
>
<p v-if="detailLoading" class="home-status">正在获取</p>
<n-alert v-else-if="detailError" type="error">{{ detailError }}</n-alert>
<div v-else-if="dialogKind === 'exam' && examDetail" class="detail">
<p v-if="examDetail.notice" class="detail-notice">{{ examDetail.notice }}</p>
<dl class="detail-facts">
<div><dt>试卷总分</dt><dd>{{ examDetail.total_score }}</dd></div>
<div><dt>合格分数</dt><dd>{{ examDetail.pass_score }}</dd></div>
<div><dt>试卷题数</dt><dd>{{ examDetail.questions }}</dd></div>
<div><dt>考试次数</dt><dd>{{ examDetail.times }}</dd></div>
<div><dt>开考时间</dt><dd>{{ examDetail.window }}</dd></div>
<div><dt>考试时限</dt><dd>{{ examDetail.limit }}</dd></div>
<div><dt>姓名</dt><dd>{{ examDetail.examinee }}</dd></div>
<div><dt>查看答卷</dt><dd>{{ examDetail.view_policy }}</dd></div>
</dl>
<h4>考试历史</h4>
<p v-if="!examDetail.attempts.length" class="home-status">没有考试记录</p>
<table v-else class="detail-table">
<thead>
<tr><th>交卷时间</th><th>考试成绩</th><th>考试结果</th></tr>
</thead>
<tbody>
<tr v-for="attempt in examDetail.attempts" :key="attempt.submitted">
<td>{{ attempt.submitted }}</td>
<td>{{ attempt.score }}</td>
<td :class="attempt.result === '通过' ? 'ok' : 'late'">{{ attempt.result }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="trainingDetail" class="detail">
<dl class="detail-facts">
<div><dt>负责人</dt><dd>{{ trainingDetail.owner || "—" }}</dd></div>
<div><dt>进度</dt><dd>{{ trainingDetail.progress }}</dd></div>
<div><dt>进度排名</dt><dd>{{ trainingDetail.rank }}</dd></div>
<div><dt>要求完成日期</dt><dd>{{ trainingDetail.deadline }}</dd></div>
<div><dt>已获总学时</dt><dd>{{ trainingDetail.earned_hours }}</dd></div>
<div><dt>实际学时</dt><dd>{{ trainingDetail.actual_hours }}</dd></div>
<div><dt>奖励学时</dt><dd>{{ trainingDetail.reward_hours }}</dd></div>
<div><dt>已获总学分</dt><dd>{{ trainingDetail.earned_credits }}</dd></div>
<div><dt>实际学分</dt><dd>{{ trainingDetail.actual_credits }}</dd></div>
<div><dt>奖励学分</dt><dd>{{ trainingDetail.reward_credits }}</dd></div>
</dl>
<section v-for="phase in trainingDetail.phases" :key="phase.name" class="phase">
<h4>{{ phase.name }}<span>{{ phase.hours }} 分钟 · {{ phase.credits }} 学分</span></h4>
<ul>
<li v-for="task in phase.tasks" :key="task.name">
<strong>{{ task.name }}</strong>
<span>{{ task.progress }}<template v-if="task.score"> · {{ task.score }} 学分</template><template v-if="task.hours"> · {{ task.hours }} 分钟</template></span>
</li>
</ul>
</section>
</div>
</n-modal>
</section>
</template>
+24
View File
@@ -106,6 +106,30 @@ export const themeOverrides = computed<GlobalThemeOverrides>(() => {
itemColorHover: current.vars["--elevated"],
borderRadius: "4px",
},
Pagination: {
itemTextColor: current.vars["--ink"],
itemTextColorHover: current.vars["--accent"],
itemTextColorPressed: current.vars["--accent"],
itemTextColorActive: current.vars["--accent"],
itemTextColorDisabled: current.vars["--muted"],
itemColor: "transparent",
itemColorHover: current.vars["--accent-soft"],
itemColorPressed: "transparent",
itemColorActive: "transparent",
itemColorActiveHover: "transparent",
itemBorder: `1px solid ${current.vars["--line"]}`,
itemBorderHover: `1px solid ${current.vars["--accent"]}`,
itemBorderPressed: `1px solid ${current.vars["--accent"]}`,
itemBorderActive: `1px solid ${current.vars["--accent"]}`,
itemBorderDisabled: `1px solid ${current.vars["--line"]}`,
buttonBorder: `1px solid ${current.vars["--line"]}`,
buttonBorderHover: `1px solid ${current.vars["--accent"]}`,
buttonBorderPressed: `1px solid ${current.vars["--accent"]}`,
buttonIconColor: current.vars["--ink"],
buttonIconColorHover: current.vars["--accent"],
buttonIconColorPressed: current.vars["--accent"],
jumperTextColor: current.vars["--muted"],
},
DataTable: {
thColor: "transparent",
tdColor: "transparent",
+211 -14
View File
@@ -351,35 +351,60 @@ select {
overflow: hidden;
}
.home-page {
.home-page,
.list-page {
overflow: hidden;
}
.home-page .page-head {
flex: none;
margin-bottom: 16px;
}
.home-page .page-head h2 {
margin: 0;
}
.home {
flex: 1;
min-height: 0;
overflow: auto;
}
.list-page {
display: flex;
flex-direction: column;
gap: 16px;
overflow: hidden;
}
.list-page > .board {
flex: 1;
min-height: 0;
}
.home-summary {
flex: none;
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 4px;
}
.home-summary .facts {
margin: 0;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.home-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.home-top-main {
min-width: 0;
flex: 1;
}
.home-refresh.n-button {
flex: none;
color: var(--muted);
}
.profile {
display: flex;
align-items: center;
@@ -460,13 +485,23 @@ select {
.board h3 {
flex: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0;
padding: 12px 16px;
padding: 8px 12px 8px 16px;
border-bottom: 1px solid var(--line);
font-size: 14px;
font-weight: 650;
}
.board-tools {
display: flex;
align-items: center;
gap: 8px;
}
.rail {
flex: 1;
min-height: 0;
@@ -678,6 +713,109 @@ select {
color: var(--muted);
}
.spin {
width: 14px;
height: 14px;
flex: none;
box-sizing: border-box;
border: 1.5px solid var(--line);
border-top-color: var(--accent);
border-radius: 50%;
animation: home-spin 0.8s linear infinite;
}
.profile .spin {
margin-left: auto;
}
.detail-loading {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 16px;
}
.detail-loading .spin {
width: 18px;
height: 18px;
}
.bone {
display: block;
background: var(--line);
border-radius: 4px;
}
.bone-copy {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.bone-avatar {
width: 48px;
height: 48px;
flex: none;
}
.bone-name {
width: 96px;
height: 14px;
}
.bone-meta {
width: 168px;
height: 12px;
}
.bone-value {
width: 52px;
height: 18px;
}
.bone-list {
list-style: none;
margin: 0;
padding: 0;
}
.bone-event {
display: grid;
gap: 8px;
padding: 14px 0 14px 24px;
}
.bone-time {
width: 140px;
height: 12px;
}
.bone-title {
width: min(240px, 86%);
height: 14px;
}
.section-error {
margin: 12px 0 0;
}
.summary-error {
margin: 0;
}
@keyframes home-spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spin {
animation: none;
}
}
@media (max-width: 800px) {
.page {
padding: 16px 12px;
@@ -710,6 +848,65 @@ select {
margin: 0;
}
.admin-page .page-head p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.course-search {
display: flex;
gap: 8px;
align-items: center;
width: min(560px, 100%);
}
.course-kinds {
flex: none;
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 0 0 12px;
}
.kind-chip {
border: 1px solid var(--line);
background: transparent;
color: var(--ink);
border-radius: 4px;
padding: 4px 10px;
font: inherit;
cursor: pointer;
}
.kind-chip span {
margin-left: 6px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.kind-chip.active {
border-color: var(--accent);
color: var(--accent);
}
.course-url {
max-width: 280px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.course-url a {
color: var(--accent);
}
.course-pager {
flex: none;
justify-content: flex-end;
margin-top: 12px;
}
.admin-page > .settings-form {
display: flex;
flex: 1;