From 4d4fe224bc86a03d3c66c3251b14affdf919b145 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 19 Nov 2026 04:08:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=85=AC=E5=91=8A?= =?UTF-8?q?=E6=A0=8F=E5=B9=B6=E8=AE=A9=E7=94=A8=E6=88=B7=E8=87=AA=E9=80=89?= =?UTF-8?q?=E5=AD=A6=E6=97=B6=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/notices.py | 103 ++++++++ backend/admin/routes.py | 35 +++ backend/admin/settings.py | 26 +- backend/admin/users.py | 9 +- .../0015_account_source_and_notices.py | 32 +++ backend/euniv/api.py | 14 ++ backend/euniv/autostudy.py | 12 +- backend/euniv/heartbeat.py | 3 + backend/euniv/models.py | 13 + backend/euniv/service.py | 17 +- backend/tests/test_admin.py | 34 +++ backend/tests/test_api.py | 6 +- backend/tests/test_autostudy.py | 8 +- web/src/features/admin/NoticesView.vue | 196 +++++++++++++++ web/src/features/admin/SettingsView.vue | 6 +- web/src/features/home/HomeView.vue | 26 +- web/src/features/home/NoticeRail.vue | 76 ++++++ web/src/shell/AdminShell.vue | 8 +- web/src/shell/adminNavigation.ts | 5 +- web/src/styles.css | 224 ++++++++++++++++-- 20 files changed, 789 insertions(+), 64 deletions(-) create mode 100644 backend/admin/notices.py create mode 100644 backend/alembic/versions/0015_account_source_and_notices.py create mode 100644 web/src/features/admin/NoticesView.vue create mode 100644 web/src/features/home/NoticeRail.vue diff --git a/backend/admin/notices.py b/backend/admin/notices.py new file mode 100644 index 0000000..88c8c5f --- /dev/null +++ b/backend/admin/notices.py @@ -0,0 +1,103 @@ +"""公告的发布和读取。""" + +from __future__ import annotations + +from datetime import datetime +from urllib.parse import urlparse + +from fastapi import HTTPException +from sqlalchemy import select +from sqlalchemy.orm import Session + +from euniv.models import Announcement +from euniv.study_window import CN_TZ + + +def _minute(value: datetime) -> datetime: + if value.tzinfo is None: + value = value.replace(tzinfo=CN_TZ) + else: + value = value.astimezone(CN_TZ) + return value.replace(second=0, microsecond=0) + + +def parse_published_at(raw: str) -> datetime: + text = (raw or "").strip() + if not text: + raise HTTPException(status_code=400, detail="请填写公告时间") + try: + parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError as exc: + raise HTTPException(status_code=400, detail="公告时间无法识别") from exc + return _minute(parsed) + + +def clean_notice(title: str, body: str, link_url: str) -> tuple[str, str, str]: + title_text = (title or "").strip() + body_text = (body or "").strip() + link = (link_url or "").strip() + if not title_text or len(title_text) > 80: + raise HTTPException(status_code=400, detail="标题须为 1 到 80 个字") + if not body_text or len(body_text) > 4000: + raise HTTPException(status_code=400, detail="正文须为 1 到 4000 个字") + if link: + if len(link) > 300: + raise HTTPException(status_code=400, detail="链接过长") + parsed = urlparse(link) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + raise HTTPException(status_code=400, detail="链接须以 http 或 https 开头") + return title_text, body_text, link + + +def _view(row: Announcement) -> dict: + published = row.published_at + if published.tzinfo is None: + published = published.replace(tzinfo=CN_TZ) + return { + "id": row.id, + "title": row.title, + "body": row.body, + "link_url": row.link_url or "", + "published_at": published.isoformat(), + } + + +def list_notices(db: Session) -> list[dict]: + rows = db.scalars(select(Announcement).order_by(Announcement.published_at.desc(), Announcement.id.desc())).all() + return [_view(row) for row in rows] + + +def create_notice(db: Session, title: str, body: str, link_url: str, published_at: str) -> dict: + title_text, body_text, link = clean_notice(title, body, link_url) + row = Announcement( + title=title_text, + body=body_text, + link_url=link, + published_at=parse_published_at(published_at), + ) + db.add(row) + db.commit() + db.refresh(row) + return _view(row) + + +def update_notice(db: Session, notice_id: int, title: str, body: str, link_url: str, published_at: str) -> dict: + row = db.get(Announcement, notice_id) + if row is None: + raise HTTPException(status_code=404, detail="公告不存在") + title_text, body_text, link = clean_notice(title, body, link_url) + row.title = title_text + row.body = body_text + row.link_url = link + row.published_at = parse_published_at(published_at) + db.commit() + return _view(row) + + +def delete_notice(db: Session, notice_id: int) -> dict: + row = db.get(Announcement, notice_id) + if row is None: + raise HTTPException(status_code=404, detail="公告不存在") + db.delete(row) + db.commit() + return {"ok": True} diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 33d89f6..aab3cce 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -44,6 +44,13 @@ class SettingsBody(BaseModel): hours_source: str = "api" +class NoticeBody(BaseModel): + title: str + body: str + link_url: str = "" + published_at: str + + class PauseBody(BaseModel): paused: bool @@ -204,6 +211,34 @@ def put_users_study_settings( ) +@admin_router.get("/notices") +def get_notices(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: + from admin.notices import list_notices + + return list_notices(db) + + +@admin_router.post("/notices") +def post_notice(body: NoticeBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + from admin.notices import create_notice + + return create_notice(db, body.title, body.body, body.link_url, body.published_at) + + +@admin_router.put("/notices/{notice_id}") +def put_notice(notice_id: int, body: NoticeBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + from admin.notices import update_notice + + return update_notice(db, notice_id, body.title, body.body, body.link_url, body.published_at) + + +@admin_router.delete("/notices/{notice_id}") +def remove_notice(notice_id: int, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + from admin.notices import delete_notice + + return delete_notice(db, notice_id) + + @admin_router.get("/users/{employee_id}/credentials") def get_credentials( employee_id: str, response: Response, db: Session = Depends(get_db), _: str = Depends(require_admin) diff --git a/backend/admin/settings.py b/backend/admin/settings.py index 71b6c3b..9172fb8 100644 --- a/backend/admin/settings.py +++ b/backend/admin/settings.py @@ -144,7 +144,7 @@ def heartbeat_intervals() -> dict: def hours_source_of(row: SystemConfig | None = None) -> str: - """api:接口本月学时;history:学时历史本月分钟合计。""" + """管理端为新用户准备的默认依据。api:官方统计;history:历史统计。""" if row is None: from euniv.db import SessionLocal @@ -154,6 +154,25 @@ def hours_source_of(row: SystemConfig | None = None) -> str: return value if value in ("api", "history") else "api" +def account_hours_source(account) -> str: + value = str(getattr(account, "hours_source", "") or "").strip().lower() + return value if value in ("api", "history") else hours_source_of() + + +def source_for_employee(employee_id: str) -> str: + from euniv.db import SessionLocal + from euniv.models import Account + + key = (employee_id or "").strip() + if not key: + return hours_source_of() + with SessionLocal() as db: + account = db.get(Account, key) + if account is None: + return hours_source_of() + return account_hours_source(account) + + def settings_view(row: SystemConfig) -> dict: return { "refresh_interval_minutes": int(row.refresh_interval_minutes), @@ -234,7 +253,6 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: row = load_config(db) previous_interval = int(row.refresh_interval_minutes) previous_username = row.admin_username - previous_source = hours_source_of(row) row.refresh_interval_minutes = interval row.show_manual_jigsaw = bool(payload.get("show_manual_jigsaw")) row.manual_preference = bool(payload.get("manual_preference")) @@ -261,8 +279,4 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: from euniv.service import notify_refresh_interval_changed notify_refresh_interval_changed() - if source != previous_source: - from euniv.service import notify_hours_source_changed - - notify_hours_source_changed() return row diff --git a/backend/admin/users.py b/backend/admin/users.py index 2c49a8a..59e4102 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -62,10 +62,9 @@ def _iso_time(value: datetime | None) -> str | None: def list_users(db: Session) -> list[dict]: - from admin.settings import hours_source_of + from admin.settings import account_hours_source from euniv.autostudy import autostudy_status, work_running - source = hours_source_of() accounts = db.scalars(select(Account).order_by(Account.employee_id)).all() live_users = autostudy_status().get("users") or {} rows = [] @@ -85,7 +84,7 @@ def list_users(db: Session) -> list[dict]: "credential_valid": _optional_bool(account.credential_valid), "month_hours": account.month_hours or "", "official_month_hours": account.official_month_hours or "", - "hours_source": source, + "hours_source": account_hours_source(account), "monthly_target": account.monthly_target if account.monthly_target is not None else 600, "has_proxy": enabled(account), "proxy": summary_of(account), @@ -116,7 +115,7 @@ def _require(db: Session, employee_id: str) -> Account: def _checked_hours(client) -> tuple[str, str]: - from admin.settings import hours_source_of + from admin.settings import source_for_employee from euniv.service import _month_hours try: @@ -124,7 +123,7 @@ def _checked_hours(client) -> tuple[str, str]: except Exception: hours = "" official = "" - if hours and hours_source_of() == "history": + if hours and source_for_employee(str(getattr(client, "login_name", "") or "")) == "history": reader = getattr(client, "month_hours", None) if callable(reader): try: diff --git a/backend/alembic/versions/0015_account_source_and_notices.py b/backend/alembic/versions/0015_account_source_and_notices.py new file mode 100644 index 0000000..7846a29 --- /dev/null +++ b/backend/alembic/versions/0015_account_source_and_notices.py @@ -0,0 +1,32 @@ +"""账号自选学时判断依据,并增加公告。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0015_account_source_and_notices" +down_revision = "0014_official_month_hours" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column(sa.Column("hours_source", sa.String(length=16), server_default="api", nullable=False)) + op.execute( + "UPDATE accounts SET hours_source = COALESCE(" + "(SELECT hours_source FROM system_config ORDER BY id LIMIT 1), 'api')" + ) + op.create_table( + "announcements", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("title", sa.String(length=80), nullable=False), + sa.Column("body", sa.Text(), nullable=False), + sa.Column("link_url", sa.String(length=300), server_default="", nullable=False), + sa.Column("published_at", sa.DateTime(timezone=True), nullable=False), + ) + + +def downgrade() -> None: + op.drop_table("announcements") + with op.batch_alter_table("accounts") as batch: + batch.drop_column("hours_source") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 4221e0b..5bc3025 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -84,6 +84,7 @@ class StudyBundleBody(BaseModel): heartbeat_video_seconds: int | None = Field(default=None, strict=True, ge=0, le=300) heartbeat_document_seconds: int | None = Field(default=None, strict=True, ge=0, le=600) heartbeat_scorm_seconds: int | None = Field(default=None, strict=True, ge=0, le=600) + hours_source: str | None = None class StudyControlBody(BaseModel): @@ -327,6 +328,14 @@ def _signed_in(request: Request, db: Session) -> str: return employee_id +@app.get("/api/announcements") +def announcements(request: Request, db: Session = Depends(get_db)) -> list[dict]: + from admin.notices import list_notices + + _signed_in(request, db) + return list_notices(db) + + @app.get("/api/home/summary") def home_summary(request: Request, db: Session = Depends(get_db)) -> dict: try: @@ -446,6 +455,11 @@ def _apply_study_bundle(account: Account, body: StudyBundleBody) -> None: body.heartbeat_document_seconds, body.heartbeat_scorm_seconds, ) + if body.hours_source is not None: + chosen = str(body.hours_source).strip().lower() + if chosen not in {"api", "history"}: + raise HTTPException(status_code=400, detail="学时判断须为官方统计或历史统计") + account.hours_source = chosen except (StudyWindowError, CourseWorkersError, HeartbeatError) as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 357ad17..4235408 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -889,9 +889,9 @@ class HoursWatcher: self.user_stop.set() return True try: - from admin.settings import hours_source_of + from admin.settings import source_for_employee - source = hours_source_of() + source = source_for_employee(self.employee_id) official = "" if source == "history": current = int(await self.session.month_history_minutes()) @@ -2104,8 +2104,6 @@ class AutoStudyWorker: async def _run_account(self, job: tuple, course_list, generation: int) -> None: emp_id, target, pw, cred, proxy, workers, use_pool = job try: - from admin.settings import hours_source_of - if int(target or 0) <= 0: if use_pool: await asyncio.to_thread(_release_pool, emp_id, True) @@ -2115,10 +2113,9 @@ class AutoStudyWorker: if use_pool: await asyncio.to_thread(_release_pool, emp_id, True) return - hours_source = await asyncio.to_thread(hours_source_of) await self._study_user( emp_id, target, pw, cred, proxy, workers, use_pool, - course_list, hours_source, + course_list, ) except Exception as exc: log.warning("用户 %s 自动学习失败: %s", emp_id, exc) @@ -2139,8 +2136,7 @@ class AutoStudyWorker: async def _study_user(self, employee_id: str, target: int, password: str, credential: dict, proxy: str | None, - workers: int, use_pool: bool, course_list: list, - hours_source: str) -> None: + workers: int, use_pool: bool, course_list: list) -> None: assert self._async_stop is not None user_stop = asyncio.Event() with _halt_lock: diff --git a/backend/euniv/heartbeat.py b/backend/euniv/heartbeat.py index 42654c9..150831a 100644 --- a/backend/euniv/heartbeat.py +++ b/backend/euniv/heartbeat.py @@ -56,11 +56,14 @@ def _stored(value: object, default: int, high: int) -> int: def view_of(account) -> dict: + from admin.settings import account_hours_source + return { "heartbeat_mode": mode_of(account), "heartbeat_video_seconds": video_of(account), "heartbeat_document_seconds": document_of(account), "heartbeat_scorm_seconds": scorm_of(account), + "hours_source": account_hours_source(account), } diff --git a/backend/euniv/models.py b/backend/euniv/models.py index e3eae1b..28571cf 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -78,6 +78,7 @@ class Account(Base): study_opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) study_schedule_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) heartbeat_mode: Mapped[str] = mapped_column(String(16), nullable=False, default="auto", server_default="auto") + hours_source: Mapped[str] = mapped_column(String(16), nullable=False, default="api", server_default="api") heartbeat_video_seconds: Mapped[int] = mapped_column(nullable=False, default=30, server_default="30") heartbeat_document_seconds: Mapped[int] = mapped_column(nullable=False, default=120, server_default="120") heartbeat_scorm_seconds: Mapped[int] = mapped_column(nullable=False, default=120, server_default="120") @@ -87,3 +88,15 @@ class Account(Base): password_login_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP") ) + + +class Announcement(Base): + """面向用户的公告。时间精确到分钟。""" + + __tablename__ = "announcements" + + id: Mapped[int] = mapped_column(primary_key=True) + title: Mapped[str] = mapped_column(String(80), nullable=False, default="") + body: Mapped[str] = mapped_column(Text, nullable=False, default="") + link_url: Mapped[str] = mapped_column(String(300), nullable=False, default="", server_default=text("''")) + published_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 37f4a71..aab43f8 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -135,7 +135,14 @@ def _persist_locked(db: Session, employee_id: str, password: str | None, client: client.authorize(profile) account = db.get(Account, employee_id) if account is None: - account = Account(employee_id=employee_id, password_cipher="", credential_cipher="") + from admin.settings import hours_source_of + + account = Account( + employee_id=employee_id, + password_cipher="", + credential_cipher="", + hours_source=hours_source_of(), + ) db.add(account) if password is None: stored = "" @@ -411,10 +418,10 @@ def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClien def _apply_hours_source(client, summary: dict, items: list | None = None) -> dict: - from admin.settings import hours_source_of + from admin.settings import source_for_employee data = dict(summary) - source = hours_source_of() + source = source_for_employee(str(getattr(client, "login_name", "") or "")) data["hours_source"] = source data["official_month_hours"] = data.get("month_hours") if source != "history": @@ -839,9 +846,9 @@ def start_credential_refresh() -> _RefreshGate: def _month_hours(client) -> str: - from admin.settings import hours_source_of + from admin.settings import source_for_employee - if hours_source_of() == "history": + if source_for_employee(str(getattr(client, "login_name", "") or "")) == "history": reader = getattr(client, "month_history_minutes", None) if reader is None: return "" diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 4414c78..b624869 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -996,3 +996,37 @@ def test_admin_can_switch_hours_source() -> None: bad = client.put("/api/admin/settings", json=_settings_body(hours_source="other")) assert bad.status_code == 400 assert bad.json()["detail"] == "学时达标依据须为 api 或 history" + + +def test_admin_can_publish_notices() -> None: + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + created = client.post( + "/api/admin/notices", + json={ + "title": "维护", + "body": "今晚更新", + "link_url": "https://euniv.asio.asia", + "published_at": "2026-11-19T04:00:00+08:00", + }, + ) + assert created.status_code == 200 + assert created.json()["title"] == "维护" + assert created.json()["published_at"].startswith("2026-11-19T04:00") + listed = client.get("/api/admin/notices") + assert listed.status_code == 200 + assert listed.json()[0]["link_url"] == "https://euniv.asio.asia" + bad = client.post( + "/api/admin/notices", + json={ + "title": "坏链接", + "body": "正文", + "link_url": "javascript:alert(1)", + "published_at": "2026-11-19T04:00:00+08:00", + }, + ) + assert bad.status_code == 400 + notice_id = created.json()["id"] + assert client.delete(f"/api/admin/notices/{notice_id}").status_code == 200 + assert client.get("/api/admin/notices").json() == [] diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 3df7050..8507b87 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -172,6 +172,7 @@ def test_login_stores_password_and_credential_only(monkeypatch) -> None: "study_opened_at", "study_schedule_enabled", "heartbeat_mode", + "hours_source", "heartbeat_video_seconds", "heartbeat_document_seconds", "heartbeat_scorm_seconds", @@ -593,7 +594,7 @@ def test_period_page_is_not_fetched_twice() -> None: return Response() client.client = HTTP() - assert client._period_minutes() == {"year": "34", "month": "12"} + assert client._period_minutes() == {"year": "34", "month": "12", "total": ""} assert len(calls) == 1 @@ -1108,6 +1109,9 @@ def _set_hours_source(value: str) -> None: with SessionLocal() as db: row = load_config(db) row.hours_source = value + account = db.get(Account, "6650000146") + if account is not None: + account.hours_source = value db.commit() diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 66da936..2e784d6 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -386,7 +386,7 @@ class _HourSession: def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None: saved: list[tuple[str, str]] = [] - monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours))) + monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours, official="": saved.append((eid, hours))) async def main() -> None: session = _HourSession("600") @@ -402,15 +402,15 @@ def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None: def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None: saved: list[tuple[str, str]] = [] - monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours))) - monkeypatch.setattr("admin.settings.hours_source_of", lambda: "history") + monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours, official="": saved.append((eid, hours))) + monkeypatch.setattr("admin.settings.source_for_employee", lambda _employee_id: "history") class _HistorySession: async def month_history_minutes(self) -> int: return 600 async def month_hours_text(self) -> str: - raise AssertionError("history 模式不应读接口本月学时") + return "126" async def main() -> None: user_stop = asyncio.Event() diff --git a/web/src/features/admin/NoticesView.vue b/web/src/features/admin/NoticesView.vue new file mode 100644 index 0000000..ff9e930 --- /dev/null +++ b/web/src/features/admin/NoticesView.vue @@ -0,0 +1,196 @@ + + + diff --git a/web/src/features/admin/SettingsView.vue b/web/src/features/admin/SettingsView.vue index c3c347d..e8fceae 100644 --- a/web/src/features/admin/SettingsView.vue +++ b/web/src/features/admin/SettingsView.vue @@ -217,12 +217,12 @@ async function save() { - 接口本月学时 - 学时历史统计 + 官方统计数据 + 历史统计数据 -

首页、学时历史和达标判断使用同一来源

+

新用户默认使用这里的选择,已有用户不受影响

diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index c792421..3cb5a51 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -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(1); const heartbeatLoaded = ref(false); +const hoursSource = ref<"api" | "history">("api"); const heartbeatMode = ref("auto"); const heartbeatVideo = ref(30); const heartbeatDocument = ref(120); @@ -487,6 +487,7 @@ function scheduleBody(): Record | 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(() => { 刷新数据 -

{{ historyHoursNote }}

{{ item.label }}
@@ -1044,6 +1046,7 @@ onUnmounted(() => {

只统计了最近 50 页

+

自动学习

@@ -1135,10 +1138,19 @@ onUnmounted(() => {
+ + + 官方统计数据 + 历史统计数据 + +

间隔越短,发送越频繁。设为 0 时连续发送,课程列表不显示倒计时。

+

+ {{ hoursSource === "history" ? "根据学习历史统计本月学时" : "根据官方接口返回进行判断(官方统计可能会延后,导致学时可能会多刷)" }} +

@@ -1175,7 +1187,7 @@ onUnmounted(() => {
-
+
-
    +
    • {{ workerTitle(row) }}
      @@ -1196,11 +1208,13 @@ onUnmounted(() => {
    +

    {{ studyHint }}

-

{{ studyHint }}

+ + +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([]); + +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; + 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 = []; + } +}); + + + diff --git a/web/src/shell/AdminShell.vue b/web/src/shell/AdminShell.vue index 3480e17..ea16811 100644 --- a/web/src/shell/AdminShell.vue +++ b/web/src/shell/AdminShell.vue @@ -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(pageFromHash()); const collapsed = ref(window.innerWidth < 800); const holdOpen = ref(false); -const pages = new Set(["users", "courses", "settings"]); +const pages = new Set(["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); } @@ -131,6 +132,7 @@ function onMenu(key: string) { + diff --git a/web/src/shell/adminNavigation.ts b/web/src/shell/adminNavigation.ts index 1bc385d..2647eff 100644 --- a/web/src/shell/adminNavigation.ts +++ b/web/src/shell/adminNavigation.ts @@ -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) }, ]; diff --git a/web/src/styles.css b/web/src/styles.css index 884d581..0c910ff 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -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; +}