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 @@
+
+
+
+ 共 {{ items.length }} 条 正在获取 还没有公告 {{ item.body }}公告
+
+
+
首页、学时历史和达标判断使用同一来源
+新用户默认使用这里的选择,已有用户不受影响
{{ historyHoursNote }}
只统计了最近 50 页
+间隔越短,发送越频繁。设为 0 时连续发送,课程列表不显示倒计时。
++ {{ hoursSource === "history" ? "根据学习历史统计本月学时" : "根据官方接口返回进行判断(官方统计可能会延后,导致学时可能会多刷)" }} +
{{ studyHint }}