From caa79d79b7a1276553c90fb2d3200df4aa76e2e0 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 15 Nov 2026 01:30:24 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=AF=8F=E6=9C=88=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=BC=80=E5=A7=8B=E5=AD=A6=E4=B9=A0=E5=B9=B6=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E8=AE=A1=E7=AE=97=E5=BF=83=E8=B7=B3=E6=91=98?= =?UTF-8?q?=E8=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/routes.py | 22 ++++ backend/admin/users.py | 32 +++++ backend/alembic/versions/0009_study_start.py | 25 ++++ backend/euniv/api.py | 32 +++++ backend/euniv/autostudy.py | 29 ++--- backend/euniv/client.py | 23 +--- backend/euniv/models.py | 4 + backend/euniv/study_window.py | 80 +++++++++++++ backend/tests/test_admin.py | 36 ++++++ backend/tests/test_api.py | 23 ++++ backend/tests/test_autostudy.py | 58 +++++++++ web/src/features/admin/UsersView.vue | 119 +++++++++++++++++++ web/src/features/home/HomeView.vue | 58 ++++++++- web/src/styles.css | 4 + 14 files changed, 510 insertions(+), 35 deletions(-) create mode 100644 backend/alembic/versions/0009_study_start.py create mode 100644 backend/euniv/study_window.py diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 3dda919..1405ecf 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -17,8 +17,10 @@ from admin.users import ( list_users, read_credentials, read_proxy, + read_study_start, set_paused, set_proxy, + set_study_start, ) from euniv.courses import course_page, request_course_sync_now from euniv.db import get_db @@ -57,6 +59,14 @@ class AdminProxyClearBody(BaseModel): employee_ids: list[str] +class AdminStudyStartBody(BaseModel): + employee_ids: list[str] + day: int + hour: int + minute: int + second: int + + def require_admin(request: Request) -> str: if not admin_session_active(request.cookies): raise HTTPException(status_code=401, detail="未登录") @@ -164,6 +174,18 @@ def get_user_proxy(employee_id: str, db: Session = Depends(get_db), _: str = Dep return read_proxy(db, employee_id) +@admin_router.put("/users/study-start") +def put_users_study_start( + body: AdminStudyStartBody, db: Session = Depends(get_db), _: str = Depends(require_admin) +) -> dict: + return set_study_start(db, body.employee_ids, body.day, body.hour, body.minute, body.second) + + +@admin_router.get("/users/{employee_id}/study-start") +def get_user_study_start(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + return read_study_start(db, employee_id) + + @admin_router.get("/users/{employee_id}/credentials") def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: return read_credentials(db, employee_id) diff --git a/backend/admin/users.py b/backend/admin/users.py index d55c4e2..cde503c 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -12,6 +12,10 @@ from sqlalchemy.orm import Session from euniv.crypto import decrypt_secret from euniv.models import Account from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of +from euniv.study_window import StudyWindowError +from euniv.study_window import apply as apply_start +from euniv.study_window import label_of as start_label +from euniv.study_window import view_of as start_view _TOKEN_KEYS = ( "ucs_token", @@ -67,6 +71,11 @@ def list_users(db: Session) -> list[dict]: "month_hours": account.month_hours or "", "has_proxy": bool(account.proxy_scheme and account.proxy_host and account.proxy_port), "proxy": summary_of(account), + "study_start": start_label(account), + "study_start_day": int(account.study_start_day or 1), + "study_start_hour": int(account.study_start_hour or 0), + "study_start_minute": int(account.study_start_minute or 0), + "study_start_second": int(account.study_start_second or 0), } for account in accounts ] @@ -217,6 +226,29 @@ def clear_proxy(db: Session, employee_ids: list[str]) -> dict: return {"ok": True, "count": len(accounts)} +def read_study_start(db: Session, employee_id: str) -> dict: + return start_view(_require(db, employee_id)) + + +def set_study_start( + db: Session, + employee_ids: list[str], + day: int, + hour: int, + minute: int, + second: int, +) -> dict: + accounts = _accounts_by_ids(db, employee_ids) + try: + for account in accounts: + apply_start(account, day, hour, minute, second) + except StudyWindowError as exc: + db.rollback() + raise HTTPException(status_code=400, detail=str(exc)) from exc + db.commit() + return {"ok": True, "count": len(accounts)} + + def delete_user(db: Session, employee_id: str) -> dict: account = _require(db, employee_id) db.delete(account) diff --git a/backend/alembic/versions/0009_study_start.py b/backend/alembic/versions/0009_study_start.py new file mode 100644 index 0000000..aa764c4 --- /dev/null +++ b/backend/alembic/versions/0009_study_start.py @@ -0,0 +1,25 @@ +"""账号每月自动学习开始时刻。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0009_study_start" +down_revision = "0008_proxy" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column(sa.Column("study_start_day", sa.Integer(), nullable=False, server_default="1")) + batch.add_column(sa.Column("study_start_hour", sa.Integer(), nullable=False, server_default="0")) + batch.add_column(sa.Column("study_start_minute", sa.Integer(), nullable=False, server_default="0")) + batch.add_column(sa.Column("study_start_second", sa.Integer(), nullable=False, server_default="0")) + + +def downgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.drop_column("study_start_second") + batch.drop_column("study_start_minute") + batch.drop_column("study_start_hour") + batch.drop_column("study_start_day") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index fd90097..d43b5a7 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -46,6 +46,13 @@ class ProxyBody(_BaseModel): password: str | None = None +class StudyStartBody(_BaseModel): + day: int + hour: int + minute: int + second: int + + @asynccontextmanager async def lifespan(_app: FastAPI): init_db() @@ -225,6 +232,31 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session = return {"monthly_target": account.monthly_target} +@app.get("/api/settings/study-start") +def get_study_start(request: Request, db: Session = Depends(get_db)) -> dict: + from euniv.study_window import view_of + + account = db.get(Account, _signed_in(request, db)) + if account is None: + raise HTTPException(status_code=401, detail="未登录") + return view_of(account) + + +@app.put("/api/settings/study-start") +def put_study_start(body: StudyStartBody, request: Request, db: Session = Depends(get_db)) -> dict: + from euniv.study_window import StudyWindowError, apply, view_of + + account = db.get(Account, _signed_in(request, db)) + if account is None: + raise HTTPException(status_code=401, detail="未登录") + try: + apply(account, body.day, body.hour, body.minute, body.second) + except StudyWindowError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + db.commit() + return view_of(account) + + @app.get("/api/settings/proxy") def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict: from euniv.proxy import view_of diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 751b373..1956450 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -14,7 +14,6 @@ from __future__ import annotations import asyncio import contextlib -import hashlib import json import logging import random @@ -25,12 +24,12 @@ from datetime import datetime, timezone import httpx from sqlalchemy import select -from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired +from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, study_encryption from euniv.models import Account, Course +from euniv.study_window import window_open log = logging.getLogger(__name__) -_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" _MAX_CONCURRENT_USERS = 8 _MAX_COURSE_PER_USER = 1 _HOURS_REFRESH_SECONDS = 300.0 @@ -102,7 +101,7 @@ def _jitter(seconds: int) -> float: def _scorm_md5(body_json: str) -> str: - return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest() + return study_encryption(body_json) def _parse_minutes(value: str) -> int: @@ -247,18 +246,7 @@ class StudySession: return resp.json() async def get_encrypt_request(self, body_json: str) -> str: - assert self._client is not None - resp = await self._client.post( - f"{EUNIV}/kng/services/KngComService.svc/GetEncryptRequest", - json={"body": body_json}, - headers={"Content-Type": "text/json", "User-Agent": USER_AGENT}, - ) - data = resp.json() - if isinstance(data, str): - data = json.loads(data) - if data.get("Status") == "OK": - return str(data["Data"]) - raise RuntimeError(f"GetEncryptRequest 失败: {data}") + return study_encryption(body_json) async def submit_video_heartbeat(self, kid: str, pkg_id: str, study_time: int, view_schedule: int) -> dict: @@ -611,7 +599,11 @@ class AutoStudyWorker: courses = db.scalars(select(Course).order_by(Course.title)).all() course_list = [(c.path, c.title, c.kind) for c in courses] eligible = [] + waiting = 0 for row in users: + if not window_open(row): + waiting += 1 + continue target = row.monthly_target or 600 current = _parse_minutes(row.month_hours) if target > 0 and current < target: @@ -628,7 +620,10 @@ class AutoStudyWorker: return if not eligible: - _set_status(running=False, message="所有用户已达标或无有效凭据") + if waiting: + _set_status(running=False, message="未到开始时间或已达标") + else: + _set_status(running=False, message="所有用户已达标或无有效凭据") return _set_status(running=True, message=f"本轮 {len(eligible)} 个用户") diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 7705a43..8dd01d3 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -365,12 +365,12 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int: return best_x -_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" +STUDY_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" -def _scorm_md5(body_json: str) -> str: - """RteApiSite.js 里的本地 MD5:hex_md5(JSON + 固定 key)。""" - return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest() +def study_encryption(body_json: str) -> str: + """播放页 RteApiSite.js 的摘要:MD5(进度 JSON + 固定 key),与 GetEncryptRequest 相同。""" + return hashlib.md5((body_json + STUDY_MD5_KEY).encode("utf-8")).hexdigest() class SessionExpired(RuntimeError): @@ -954,18 +954,7 @@ class EunivClient: return resp.json() def get_encrypt_request(self, body_json: str) -> str: - """POST GetEncryptRequest,返回 32 位 MD5 摘要。""" - resp = self.client.post( - f"{EUNIV}/kng/services/KngComService.svc/GetEncryptRequest", - json={"body": body_json}, - headers={"Content-Type": "text/json", "User-Agent": USER_AGENT}, - ) - data = resp.json() - if isinstance(data, str): - data = json.loads(data) - if data.get("Status") == "OK": - return str(data["Data"]) - raise RuntimeError(f"GetEncryptRequest 失败: {data}") + return study_encryption(body_json) def submit_video_heartbeat(self, knowledge_id: str, package_id: str, study_time: int, view_schedule: int, @@ -1050,7 +1039,7 @@ class EunivClient: "viewSchedule": 0, } if end: - encryption = _scorm_md5(json.dumps(param, separators=(",", ":"))) + encryption = study_encryption(json.dumps(param, separators=(",", ":"))) else: encrypt_body = json.dumps(param, separators=(",", ":")) encryption = self.get_encrypt_request(encrypt_body) diff --git a/backend/euniv/models.py b/backend/euniv/models.py index 224c63e..b44fecd 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -52,3 +52,7 @@ class Account(Base): proxy_port: Mapped[int | None] = mapped_column(nullable=True) proxy_username: Mapped[str] = mapped_column(String(128), nullable=False, default="", server_default="") proxy_password_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="") + study_start_day: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1") + study_start_hour: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") + study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") + study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") diff --git a/backend/euniv/study_window.py b/backend/euniv/study_window.py new file mode 100644 index 0000000..de751eb --- /dev/null +++ b/backend/euniv/study_window.py @@ -0,0 +1,80 @@ +"""每月自动学习开始时刻。精确到秒,按北京时间判断当月是否已到点。""" + +from __future__ import annotations + +import calendar +from datetime import datetime, timedelta, timezone + +CN_TZ = timezone(timedelta(hours=8)) + + +class StudyWindowError(ValueError): + """开始时刻不符合要求。""" + + +def validate_start(day: object, hour: object, minute: object, second: object) -> tuple[int, int, int, int]: + for name, value, low, high in ( + ("日", day, 1, 31), + ("时", hour, 0, 23), + ("分", minute, 0, 59), + ("秒", second, 0, 59), + ): + if not isinstance(value, int) or isinstance(value, bool) or not low <= value <= high: + raise StudyWindowError(f"每月开始{name}须为 {low} 到 {high} 的整数") + return int(day), int(hour), int(minute), int(second) + + +def apply(account, day: object, hour: object, minute: object, second: object) -> None: + d, h, m, s = validate_start(day, hour, minute, second) + account.study_start_day = d + account.study_start_hour = h + account.study_start_minute = m + account.study_start_second = s + + +def label_of(account) -> str: + day = int(getattr(account, "study_start_day", 1) or 1) + hour = int(getattr(account, "study_start_hour", 0) or 0) + minute = int(getattr(account, "study_start_minute", 0) or 0) + second = int(getattr(account, "study_start_second", 0) or 0) + return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}" + + +def view_of(account) -> dict: + day = int(getattr(account, "study_start_day", 1) or 1) + hour = int(getattr(account, "study_start_hour", 0) or 0) + minute = int(getattr(account, "study_start_minute", 0) or 0) + second = int(getattr(account, "study_start_second", 0) or 0) + return { + "day": day, + "hour": hour, + "minute": minute, + "second": second, + "label": label_of(account), + } + + +def window_open(account, now: datetime | None = None) -> bool: + """当前是否已过该账号本月开始时刻。2 月 31 日等按当月最后一天。""" + current = now or datetime.now(CN_TZ) + if current.tzinfo is None: + current = current.replace(tzinfo=CN_TZ) + else: + current = current.astimezone(CN_TZ) + day, hour, minute, second = validate_start( + int(getattr(account, "study_start_day", 1) or 1), + int(getattr(account, "study_start_hour", 0) or 0), + int(getattr(account, "study_start_minute", 0) or 0), + int(getattr(account, "study_start_second", 0) or 0), + ) + last = calendar.monthrange(current.year, current.month)[1] + start = datetime( + current.year, + current.month, + min(day, last), + hour, + minute, + second, + tzinfo=CN_TZ, + ) + return current >= start diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index a0baeae..0f3f5ac 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -447,6 +447,11 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None: "month_hours", "has_proxy", "proxy", + "study_start", + "study_start_day", + "study_start_hour", + "study_start_minute", + "study_start_second", } assert saved["has_credential"] is True assert saved["refresh_paused"] is False @@ -690,3 +695,34 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: detail = client.get("/api/admin/users/p1-user/proxy") assert detail.json()["has_password"] is False assert detail.json()["username"] == "" + + +def test_admin_can_set_study_start_for_selected_users() -> None: + _add_account("s1-user") + _add_account("s2-user") + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + saved = client.put( + "/api/admin/users/study-start", + json={"employee_ids": ["s1-user", "s2-user"], "day": 5, "hour": 16, "minute": 8, "second": 9}, + ) + assert saved.status_code == 200 + assert saved.json()["count"] == 2 + listed = client.get("/api/admin/users").json() + one = next(item for item in listed if item["employee_id"] == "s1-user") + two = next(item for item in listed if item["employee_id"] == "s2-user") + assert one["study_start"] == "每月5日 16:08:09" + assert two["study_start"] == "每月5日 16:08:09" + one_only = client.put( + "/api/admin/users/study-start", + json={"employee_ids": ["s1-user"], "day": 20, "hour": 0, "minute": 0, "second": 0}, + ) + assert one_only.status_code == 200 + listed = client.get("/api/admin/users").json() + one = next(item for item in listed if item["employee_id"] == "s1-user") + two = next(item for item in listed if item["employee_id"] == "s2-user") + assert one["study_start"] == "每月20日 00:00:00" + assert two["study_start"] == "每月5日 16:08:09" + detail = client.get("/api/admin/users/s1-user/study-start") + assert detail.json()["day"] == 20 diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index b978e95..8f226df 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -117,6 +117,10 @@ def test_login_stores_password_and_credential_only() -> None: "proxy_port", "proxy_username", "proxy_password_cipher", + "study_start_day", + "study_start_hour", + "study_start_minute", + "study_start_second", } home = client.get("/api/home") @@ -488,6 +492,25 @@ def test_user_can_set_proxy_with_or_without_password() -> None: assert cleared.json()["enabled"] is False +def test_user_can_set_monthly_study_start() -> 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 + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + empty = client.get("/api/settings/study-start") + assert empty.status_code == 200 + assert empty.json() == {"day": 1, "hour": 0, "minute": 0, "second": 0, "label": "每月1日 00:00:00"} + saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7}) + assert saved.status_code == 200 + assert saved.json()["label"] == "每月5日 16:00:07" + bad = client.put("/api/settings/study-start", json={"day": 32, "hour": 16, "minute": 0, "second": 0}) + assert bad.status_code == 400 + + def test_exam_list_rejects_unrecognized_page() -> None: from euniv.client import EunivClient diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index ec11110..22b7bbf 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -2,8 +2,12 @@ import asyncio import pytest +from datetime import datetime + from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop +from euniv.client import study_encryption from euniv.proxy import ProxyError, build_proxy_url, parse_proxy +from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open def test_parse_proxy_accepts_http_and_socks() -> None: @@ -160,3 +164,57 @@ def test_video_skip_already_complete_does_not_refresh() -> None: assert not watcher.reached asyncio.run(main()) + + +def test_study_encryption_matches_get_encrypt_request() -> None: + import json + + body = json.dumps( + { + "knowledgeId": "6d16a38ebdfe455fbb1e86ec0c0c35d7", + "masterId": "", + "masterType": "", + "packageId": "", + "pageSize": 1, + "studySize": 1, + "studyTime": 120, + "type": 1, + "offLine": False, + "end": False, + "care": True, + "deviceId": "", + "studyChapterIds": "", + "viewSchedule": 1, + }, + separators=(",", ":"), + ) + assert study_encryption(body) == "ba119ee448648d9f8f046d11c426afa4" + + +class _Start: + def __init__(self, day: int, hour: int = 16, minute: int = 0, second: int = 0) -> None: + self.study_start_day = day + self.study_start_hour = hour + self.study_start_minute = minute + self.study_start_second = second + + +def test_study_window_opens_after_configured_time() -> None: + account = _Start(5, 16, 0, 0) + assert window_open(account, datetime(2026, 11, 5, 15, 59, 59, tzinfo=CN_TZ)) is False + assert window_open(account, datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)) is True + assert window_open(account, datetime(2026, 11, 15, 1, 24, 0, tzinfo=CN_TZ)) is True + assert window_open(account, datetime(2026, 12, 5, 15, 0, 0, tzinfo=CN_TZ)) is False + + +def test_study_window_clamps_missing_day() -> None: + account = _Start(31, 16, 0, 0) + assert window_open(account, datetime(2026, 2, 28, 15, 59, 59, tzinfo=CN_TZ)) is False + assert window_open(account, datetime(2026, 2, 28, 16, 0, 0, tzinfo=CN_TZ)) is True + + +def test_study_window_rejects_invalid_parts() -> None: + with pytest.raises(StudyWindowError): + validate_start(32, 0, 0, 0) + with pytest.raises(StudyWindowError): + validate_start(1, 24, 0, 0) diff --git a/web/src/features/admin/UsersView.vue b/web/src/features/admin/UsersView.vue index a2b8621..c81190a 100644 --- a/web/src/features/admin/UsersView.vue +++ b/web/src/features/admin/UsersView.vue @@ -12,6 +12,11 @@ interface UserRow { month_hours: string; has_proxy: boolean; proxy: string; + study_start: string; + study_start_day: number; + study_start_hour: number; + study_start_minute: number; + study_start_second: number; } interface SecretField { @@ -49,6 +54,14 @@ const proxyOptions = [ { label: "SOCKS4", value: "socks4" }, { label: "SOCKS5", value: "socks5" }, ]; +const startOpen = ref(false); +const startSaving = ref(false); +const startError = ref(""); +const startIds = ref([]); +const startDay = ref(1); +const startHour = ref(0); +const startMinute = ref(0); +const startSecond = ref(0); const pickedIds = computed(() => users.value.filter((row) => picked.value[row.employee_id]).map((row) => row.employee_id)); const allPicked = computed(() => users.value.length > 0 && pickedIds.value.length === users.value.length); @@ -93,6 +106,11 @@ function asUser(value: unknown): UserRow | null { month_hours: textOf(value.month_hours), has_proxy: value.has_proxy === true, proxy: textOf(value.proxy), + study_start: textOf(value.study_start), + study_start_day: typeof value.study_start_day === "number" ? value.study_start_day : 1, + study_start_hour: typeof value.study_start_hour === "number" ? value.study_start_hour : 0, + study_start_minute: typeof value.study_start_minute === "number" ? value.study_start_minute : 0, + study_start_second: typeof value.study_start_second === "number" ? value.study_start_second : 0, }; } @@ -428,6 +446,69 @@ function confirmClearProxy(ids: string[]) { }); } +function resetStartForm() { + startDay.value = 1; + startHour.value = 0; + startMinute.value = 0; + startSecond.value = 0; + startError.value = ""; +} + +function openStart(ids: string[]) { + if (!ids.length) return; + startIds.value = ids; + resetStartForm(); + if (ids.length === 1) { + const row = users.value.find((item) => item.employee_id === ids[0]); + if (row) { + startDay.value = row.study_start_day; + startHour.value = row.study_start_hour; + startMinute.value = row.study_start_minute; + startSecond.value = row.study_start_second; + } + } + startOpen.value = true; +} + +async function saveStart() { + if (startSaving.value || !startIds.value.length) return; + startError.value = ""; + if ( + startDay.value == null || startHour.value == null + || startMinute.value == null || startSecond.value == null + || !Number.isInteger(startDay.value) || !Number.isInteger(startHour.value) + || !Number.isInteger(startMinute.value) || !Number.isInteger(startSecond.value) + ) { + startError.value = "请填写完整的开始时刻"; + return; + } + startSaving.value = true; + try { + const response = await fetch("/api/admin/users/study-start", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + employee_ids: startIds.value, + day: startDay.value, + hour: startHour.value, + minute: startMinute.value, + second: startSecond.value, + }), + }); + const payload: unknown = await response.json().catch(() => ({})); + if (!response.ok) { + startError.value = detailOf(payload, "没有保存。"); + return; + } + startOpen.value = false; + await load(); + } catch { + startError.value = "没有保存。"; + } finally { + startSaving.value = false; + } +} + function rowActions(row: UserRow): DropdownOption[] { const busy = checkingAll.value || checkingId.value !== ""; return [ @@ -435,6 +516,7 @@ function rowActions(row: UserRow): DropdownOption[] { { label: "查看凭据", key: "credentials" }, { label: "设置代理", key: "proxy" }, { label: "清除代理", key: "proxy-clear" }, + { label: "开始时刻", key: "start" }, { label: row.refresh_paused ? "恢复自动刷新" : "停止自动刷新", key: "refresh" }, { label: "删除", key: "delete", props: { style: { color: "var(--danger)" } } }, ]; @@ -445,6 +527,7 @@ function onRowAction(row: UserRow, key: string | number) { else if (key === "credentials") void openCredentials(row); else if (key === "proxy") void openProxy([row.employee_id]); else if (key === "proxy-clear") confirmClearProxy([row.employee_id]); + else if (key === "start") openStart([row.employee_id]); else if (key === "refresh") confirmRefresh(row); else if (key === "delete") confirmDelete(row); } @@ -461,6 +544,7 @@ onMounted(() => {
设置代理 清除代理 + 开始时刻 检查全部
@@ -477,6 +561,7 @@ onMounted(() => { 凭证 凭据是否有效 本月学时 + 开始时刻 代理 上次刷新时间 自动刷新 @@ -492,6 +577,7 @@ onMounted(() => { {{ row.has_credential ? "已保存凭证" : "未保存凭证" }} {{ validityText(row) }} {{ row.month_hours || "—" }} + {{ row.study_start || "—" }} {{ row.proxy || "—" }} {{ formatRefreshTime(row.last_refresh_at) }} {{ row.refresh_paused ? "已停止" : "开启" }} @@ -574,5 +660,38 @@ onMounted(() => { + + {{ startError }} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 4e3f0a2..2249dc5 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -136,6 +136,50 @@ function saveTarget(value: number | null) { watch(monthlyTarget, (v) => { if (targetLoaded.value) saveTarget(v); }); +const startLoaded = ref(false); +const startDay = ref(1); +const startHour = ref(0); +const startMinute = ref(0); +const startSecond = ref(0); +let startSaveTimer: ReturnType | undefined; + +async function loadStart() { + try { + const res = await fetch("/api/settings/study-start"); + if (res.ok) { + const data = await res.json(); + startDay.value = typeof data.day === "number" ? data.day : 1; + startHour.value = typeof data.hour === "number" ? data.hour : 0; + startMinute.value = typeof data.minute === "number" ? data.minute : 0; + startSecond.value = typeof data.second === "number" ? data.second : 0; + startLoaded.value = true; + } + } catch { /* 静默 */ } +} + +function saveStart() { + const day = startDay.value; + const hour = startHour.value; + const minute = startMinute.value; + const second = startSecond.value; + if ( + day == null || hour == null || minute == null || second == null + || !Number.isInteger(day) || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second) + ) return; + clearTimeout(startSaveTimer); + startSaveTimer = setTimeout(async () => { + try { + await fetch("/api/settings/study-start", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ day, hour, minute, second }), + }); + } catch { /* 静默 */ } + }, 600); +} + +watch([startDay, startHour, startMinute, startSecond], () => { if (startLoaded.value) saveStart(); }); + const proxyLoaded = ref(false); const proxySaving = ref(false); const proxyError = ref(""); @@ -242,7 +286,7 @@ async function loadStudyStatus() { } catch { /* 静默 */ } } -onMounted(() => { refresh(); loadTarget(); loadProxy(); loadStudyStatus(); }); +onMounted(() => { refresh(); loadTarget(); loadStart(); loadProxy(); loadStudyStatus(); });