From e98cc13061627769e80d1427f3795fb1d3d145ef Mon Sep 17 00:00:00 2001 From: Nixevol Date: Tue, 17 Nov 2026 16:27:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=82=B9=E7=AB=8B=E5=8D=B3=E5=BC=80?= =?UTF-8?q?=E5=A7=8B=E6=97=B6=E6=8C=89=E5=BD=93=E5=89=8D=E8=A1=A8=E5=8D=95?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=90=AF=E5=8A=A8=E5=B9=B6=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E4=BF=9D=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/api.py | 38 +++++++++++---- backend/tests/test_api.py | 66 +++++++++++++++++++++++++ web/src/features/home/HomeView.vue | 77 +++++++++++++++++++----------- 3 files changed, 143 insertions(+), 38 deletions(-) diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 8c2e3f3..acac916 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -88,6 +88,7 @@ class StudyBundleBody(BaseModel): class StudyControlBody(BaseModel): action: str = Field(min_length=1, max_length=16) + settings: StudyBundleBody | None = None @asynccontextmanager @@ -426,17 +427,12 @@ def get_heartbeat(request: Request, db: Session = Depends(get_db)) -> dict: return view_of(account) -@app.put("/api/settings/study") -def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict: +def _apply_study_bundle(account: Account, body: StudyBundleBody) -> None: + """把首页这一组学习配置写到账号上。不符合要求时抛 400,由调用方回滚。""" from euniv.course_workers import CourseWorkersError, apply as apply_workers - from euniv.heartbeat import HeartbeatError, apply as apply_heartbeat, view_of as heartbeat_view - from euniv.study_window import StudyWindowError, apply as apply_start, view_of + from euniv.heartbeat import HeartbeatError, apply as apply_heartbeat + from euniv.study_window import StudyWindowError, apply as apply_start - if not 0 <= body.monthly_target <= 9999: - raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") - account = db.get(Account, _signed_in(request, db)) - if account is None: - raise HTTPException(status_code=401, detail="未登录") try: account.monthly_target = body.monthly_target apply_start(account, body.day, body.hour, body.minute, body.second) @@ -456,8 +452,22 @@ def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depe body.heartbeat_scorm_seconds, ) except (StudyWindowError, CourseWorkersError, HeartbeatError) as exc: - db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@app.put("/api/settings/study") +def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict: + from euniv.heartbeat import view_of as heartbeat_view + 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="未登录") + try: + _apply_study_bundle(account, body) + except HTTPException: + db.rollback() + raise db.commit() from euniv.autostudy import sync_work @@ -549,11 +559,19 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D raise HTTPException(status_code=401, detail="未登录") action = (body.action or "").strip().lower() if action == "start": + if body.settings is not None: + try: + _apply_study_bundle(account, body.settings) + except HTTPException: + db.rollback() + raise if int(account.monthly_target or 0) <= 0: + db.rollback() raise HTTPException(status_code=400, detail="每月目标为 0,不会学习") if hours_met(account): from euniv.autostudy import halt_work + db.commit() halt_work(employee_id) else: from euniv.autostudy import clear_study_hold diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index e1b2027..47262d5 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -816,6 +816,72 @@ def test_user_can_start_and_stop_study_immediately(monkeypatch) -> None: assert bad.status_code == 400 +def test_start_saves_the_settings_sent_with_it(monkeypatch) -> None: + import euniv.api as api_module + import euniv.service as service_module + from euniv.autostudy import work_running + + monkeypatch.setattr( + 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) + _freeze_beijing(monkeypatch, 2026, 11, 15) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + settings = _study_body( + monthly_target=900, + day=20, + hour=6, + minute=30, + second=5, + enabled=False, + workers=3, + heartbeat_mode="manual", + heartbeat_video_seconds=0, + heartbeat_document_seconds=7, + heartbeat_scorm_seconds=9, + ) + started = client.post("/api/settings/study-control", json={"action": "start", "settings": settings}) + assert started.status_code == 200 + assert started.json()["started"] is True + assert started.json()["monthly_target"] == 900 + assert work_running("6650000146") is True + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + assert account.monthly_target == 900 + assert (account.study_start_day, account.study_start_hour) == (20, 6) + assert (account.study_start_minute, account.study_start_second) == (30, 5) + assert account.study_schedule_enabled is False + assert account.course_workers == 3 + assert account.heartbeat_mode == "manual" + assert account.heartbeat_video_seconds == 0 + assert account.heartbeat_document_seconds == 7 + assert account.heartbeat_scorm_seconds == 9 + client.post("/api/settings/study-control", json={"action": "stop"}) + rejected = client.post( + "/api/settings/study-control", + json={"action": "start", "settings": _study_body(monthly_target=0, workers=5)}, + ) + assert rejected.status_code == 400 + assert rejected.json()["detail"] == "每月目标为 0,不会学习" + bad = client.post( + "/api/settings/study-control", + json={"action": "start", "settings": _study_body(workers=9)}, + ) + assert bad.status_code == 400 + assert bad.json()["detail"] == "同时学习课程数须为 1 到 8" + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + assert account.monthly_target == 900 + assert account.course_workers == 3 + assert work_running("6650000146") is False + + def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index b7dde46..ff84b59 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -115,6 +115,14 @@ const studyLabel = computed(() => { return "等待启动"; }); +const startBlocked = computed(() => { + if (!scheduleReady.value) return "正在读取配置"; + const target = monthlyTarget.value ?? 0; + if (target <= 0) return "请先把每月目标设为大于 0"; + if (monthProgress.value.current >= target) return "本月学时已达到目标,把目标改大后可以再开始"; + return ""; +}); + const studyHint = computed(() => { if (studyingWorkers.value.length) return ""; if (progressTarget.value <= 0) return "请先设置每月目标。"; @@ -376,8 +384,7 @@ async function putJson(url: string, body: Record, fallback: str if (!res.ok) throw new Error(failureText(data, fallback)); } -async function saveSchedule() { - if (scheduleSaving.value || !scheduleReady.value) return; +function scheduleBody(): Record | null { const target = monthlyTarget.value; const day = startDay.value; const hour = startHour.value; @@ -386,7 +393,7 @@ async function saveSchedule() { const workers = courseWorkers.value; if (target == null || !Number.isInteger(target) || target < 0 || target > 9999) { scheduleError.value = "每月学时目标须为 0 到 9999 的整数"; - return; + return null; } if ( day == null || hour == null || minute == null || second == null @@ -394,50 +401,57 @@ async function saveSchedule() { || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59 ) { scheduleError.value = "请填写完整的开始时刻"; - return; + return null; } if (day < STUDY_DAY_MIN || day > STUDY_DAY_MAX) { scheduleError.value = "每月开始日须为 5 到 25 的整数"; - return; + return null; } if (workers == null || !Number.isInteger(workers) || workers < 1 || workers > 8) { scheduleError.value = "同时学习课程数须为 1 到 8"; - return; + return null; } if (heartbeatMode.value !== "auto" && heartbeatMode.value !== "manual") { scheduleError.value = "心跳间隔须为自动获取或手动设定"; - return; + return null; } if (heartbeatMode.value === "manual") { if (heartbeatVideo.value == null || !Number.isInteger(heartbeatVideo.value) || heartbeatVideo.value < 0 || heartbeatVideo.value > 300) { scheduleError.value = "视频心跳间隔须为 0 到 300 的整数"; - return; + return null; } if (heartbeatDocument.value == null || !Number.isInteger(heartbeatDocument.value) || heartbeatDocument.value < 0 || heartbeatDocument.value > 600) { scheduleError.value = "文档心跳间隔须为 0 到 600 的整数"; - return; + return null; } if (heartbeatScorm.value == null || !Number.isInteger(heartbeatScorm.value) || heartbeatScorm.value < 0 || heartbeatScorm.value > 600) { scheduleError.value = "Scorm 心跳间隔须为 0 到 600 的整数"; - return; + return null; } } - scheduleSaving.value = true; scheduleError.value = ""; + return { + monthly_target: target, + day, + hour, + minute, + second, + enabled: scheduleEnabled.value, + workers, + heartbeat_mode: heartbeatMode.value, + heartbeat_video_seconds: heartbeatVideo.value ?? 30, + heartbeat_document_seconds: heartbeatDocument.value ?? 120, + heartbeat_scorm_seconds: heartbeatScorm.value ?? 120, + }; +} + +async function saveSchedule() { + if (scheduleSaving.value || !scheduleReady.value) return; + const body = scheduleBody(); + if (!body) return; + scheduleSaving.value = true; try { - await putJson("/api/settings/study", { - monthly_target: target, - day, - hour, - minute, - second, - enabled: scheduleEnabled.value, - workers, - heartbeat_mode: heartbeatMode.value, - heartbeat_video_seconds: heartbeatVideo.value ?? 30, - heartbeat_document_seconds: heartbeatDocument.value ?? 120, - heartbeat_scorm_seconds: heartbeatScorm.value ?? 120, - }, "没有保存定时配置。"); + await putJson("/api/settings/study", body, "没有保存定时配置。"); await loadStudyControl(); } catch (exc) { scheduleError.value = exc instanceof Error ? exc.message : "没有保存。"; @@ -811,14 +825,21 @@ watch([countdownOn, showHoursRefresh], ([heart, hours]) => { async function toggleStudy() { if (studyBusy.value) return; + const action = studyControl.value.started ? "stop" : "start"; + const request: Record = { action }; + if (action === "start") { + if (!scheduleReady.value) return; + const settings = scheduleBody(); + if (!settings) return; + request.settings = settings; + } studyBusy.value = true; studyError.value = ""; - const action = studyControl.value.started ? "stop" : "start"; try { const res = await apiFetch("/api/settings/study-control", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ action }), + body: JSON.stringify(request), }); const data = await res.json().catch(() => ({})); if (!res.ok) { @@ -992,7 +1013,7 @@ onUnmounted(() => { - {{ studyControl.hours_met ? "本月目标已达到" : progressTarget <= 0 ? "请先设置每月目标。" : "会跳过设定的定时启动时间,立刻开始学习任务。" }} + {{ startBlocked || "按左边当前的配置立刻开始,并保存这份配置" }}