feat: 学习进度轮询、学时依据与首页代理弹窗
This commit is contained in:
@@ -22,3 +22,4 @@ class SystemConfig(Base):
|
||||
heartbeat_video_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=30, server_default="30")
|
||||
heartbeat_document_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=120, server_default="120")
|
||||
heartbeat_scorm_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=120, server_default="120")
|
||||
hours_source: Mapped[str] = mapped_column(String(16), nullable=False, default="api", server_default="api")
|
||||
|
||||
@@ -49,6 +49,7 @@ class SettingsBody(BaseModel):
|
||||
heartbeat_video_seconds: int = 30
|
||||
heartbeat_document_seconds: int = 120
|
||||
heartbeat_scorm_seconds: int = 120
|
||||
hours_source: str = "api"
|
||||
|
||||
|
||||
class PauseBody(BaseModel):
|
||||
|
||||
@@ -85,6 +85,17 @@ def heartbeat_intervals(db: Session | None = None) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def hours_source_of(row: SystemConfig | None = None) -> str:
|
||||
"""api:接口本月学时;history:学时历史本月分钟合计。"""
|
||||
if row is None:
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
with SessionLocal() as owned:
|
||||
return hours_source_of(load_config(owned))
|
||||
value = str(row.hours_source or "api").strip().lower()
|
||||
return value if value in ("api", "history") else "api"
|
||||
|
||||
|
||||
def settings_view(row: SystemConfig) -> dict:
|
||||
return {
|
||||
"refresh_interval_minutes": int(row.refresh_interval_minutes),
|
||||
@@ -96,6 +107,7 @@ def settings_view(row: SystemConfig) -> dict:
|
||||
"heartbeat_video_seconds": int(row.heartbeat_video_seconds),
|
||||
"heartbeat_document_seconds": int(row.heartbeat_document_seconds),
|
||||
"heartbeat_scorm_seconds": int(row.heartbeat_scorm_seconds),
|
||||
"hours_source": hours_source_of(row),
|
||||
}
|
||||
|
||||
|
||||
@@ -150,6 +162,9 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
|
||||
raise SettingsError("文档心跳间隔须为 30 到 600 的整数")
|
||||
if hb_scorm is None or not 30 <= hb_scorm <= 600:
|
||||
raise SettingsError("Scorm 心跳间隔须为 30 到 600 的整数")
|
||||
source = str(payload.get("hours_source") or "api").strip().lower()
|
||||
if source not in ("api", "history"):
|
||||
raise SettingsError("学时达标依据须为 api 或 history")
|
||||
|
||||
row = load_config(db)
|
||||
previous_interval = int(row.refresh_interval_minutes)
|
||||
@@ -162,6 +177,7 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
|
||||
row.heartbeat_video_seconds = hb_video
|
||||
row.heartbeat_document_seconds = hb_doc
|
||||
row.heartbeat_scorm_seconds = hb_scorm
|
||||
row.hours_source = source
|
||||
if password is not None and password != "":
|
||||
row.admin_password_cipher = encrypt_secret(str(password))
|
||||
db.commit()
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""学时达标判断依据:接口本月学时或学时历史统计。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0013_hours_source"
|
||||
down_revision = "0012_study_control"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("system_config") as batch:
|
||||
batch.add_column(
|
||||
sa.Column("hours_source", sa.String(length=16), nullable=False, server_default="api")
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("system_config") as batch:
|
||||
batch.drop_column("hours_source")
|
||||
@@ -354,6 +354,9 @@ def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
live = (autostudy_status().get("users") or {}).get(employee_id) or {}
|
||||
payload["state"] = str(live.get("state") or "")
|
||||
payload["course"] = str(live.get("course") or "")
|
||||
payload["message"] = str(live.get("message") or "")
|
||||
workers = live.get("workers") or []
|
||||
payload["workers"] = workers if isinstance(workers, list) else []
|
||||
payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
|
||||
if payload["active"]:
|
||||
payload["started"] = True
|
||||
|
||||
+230
-48
@@ -19,6 +19,7 @@ import logging
|
||||
import random
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import httpx
|
||||
@@ -42,9 +43,32 @@ _user_halts: dict[str, asyncio.Event] = {}
|
||||
_worker = None
|
||||
|
||||
|
||||
def _workers_list(info: dict) -> list[dict]:
|
||||
workers = info.get("workers") or {}
|
||||
if isinstance(workers, list):
|
||||
return [dict(item) for item in workers if isinstance(item, dict)]
|
||||
if not isinstance(workers, dict):
|
||||
return []
|
||||
rows = []
|
||||
for key in sorted(workers, key=lambda value: int(value) if str(value).isdigit() else 0):
|
||||
item = workers[key]
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
row = dict(item)
|
||||
row.setdefault("id", int(key) if str(key).isdigit() else key)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def autostudy_status() -> dict:
|
||||
with _lock:
|
||||
return dict(_status)
|
||||
raw = {key: value for key, value in _status.items() if key != "users"}
|
||||
users_in = dict(_status.get("users") or {})
|
||||
copied = {eid: dict(info) for eid, info in users_in.items()}
|
||||
for info in copied.values():
|
||||
info["workers"] = _workers_list(info)
|
||||
raw["users"] = copied
|
||||
return raw
|
||||
|
||||
|
||||
def _set_status(**kw: object) -> None:
|
||||
@@ -66,6 +90,46 @@ def _clear_user_status(employee_id: str) -> None:
|
||||
_status.get("users", {}).pop(employee_id, None)
|
||||
|
||||
|
||||
def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None:
|
||||
with _lock:
|
||||
users = _status.setdefault("users", {})
|
||||
info = users.setdefault(employee_id, {})
|
||||
workers = info.setdefault("workers", {})
|
||||
if not isinstance(workers, dict):
|
||||
workers = {}
|
||||
info["workers"] = workers
|
||||
row = workers.setdefault(str(worker_id), {"id": worker_id})
|
||||
row.update(kw)
|
||||
course = kw.get("course")
|
||||
if isinstance(course, str) and course:
|
||||
info["course"] = course
|
||||
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
class WorkerView:
|
||||
def __init__(self, employee_id: str, worker_id: int) -> None:
|
||||
self.employee_id = employee_id
|
||||
self.worker_id = worker_id
|
||||
|
||||
def update(self, **kw: object) -> None:
|
||||
_set_worker_status(self.employee_id, self.worker_id, **kw)
|
||||
|
||||
|
||||
def _touch(worker: WorkerView | None, **kw: object) -> None:
|
||||
if worker is not None:
|
||||
worker.update(**kw)
|
||||
|
||||
|
||||
def _progress_of(payload: dict) -> float:
|
||||
raw = payload.get("studyschedule")
|
||||
if raw is None:
|
||||
raw = payload.get("studySchedule")
|
||||
try:
|
||||
return max(0.0, min(100.0, float(raw or 0)))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def request_stop(employee_id: str) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
@@ -160,12 +224,14 @@ class HoursWatcher:
|
||||
target: int,
|
||||
user_stop: asyncio.Event,
|
||||
interval: float = _HOURS_REFRESH_SECONDS,
|
||||
source: str = "api",
|
||||
) -> None:
|
||||
self.session = session
|
||||
self.employee_id = employee_id
|
||||
self.target = target
|
||||
self.user_stop = user_stop
|
||||
self.interval = interval
|
||||
self.source = source if source in ("api", "history") else "api"
|
||||
self._lock = asyncio.Lock()
|
||||
self.reached = False
|
||||
|
||||
@@ -174,8 +240,12 @@ class HoursWatcher:
|
||||
if self.reached or self.user_stop.is_set():
|
||||
return True
|
||||
try:
|
||||
text = await self.session.month_hours_text()
|
||||
current = _parse_minutes(text)
|
||||
if self.source == "history":
|
||||
current = int(await self.session.month_history_minutes())
|
||||
text = str(current)
|
||||
else:
|
||||
text = await self.session.month_hours_text()
|
||||
current = _parse_minutes(text)
|
||||
if text:
|
||||
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
|
||||
if current >= self.target:
|
||||
@@ -456,6 +526,51 @@ class StudySession:
|
||||
m = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', resp.text)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
async def month_history_minutes(self, now: datetime | None = None) -> int:
|
||||
from euniv.client import (
|
||||
HISTORY_PAGE_SIZE,
|
||||
fold_month_minutes,
|
||||
history_items_from_payload,
|
||||
history_search_body,
|
||||
)
|
||||
from euniv.study_window import CN_TZ
|
||||
|
||||
current = now or datetime.now(CN_TZ)
|
||||
year, month = current.year, current.month
|
||||
offset = 0
|
||||
total = 0
|
||||
first_mark: tuple | None = None
|
||||
for _ in range(50):
|
||||
resp = await self._api(
|
||||
"POST",
|
||||
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
|
||||
json=history_search_body(True, offset, HISTORY_PAGE_SIZE),
|
||||
)
|
||||
rows = history_items_from_payload(resp.json())
|
||||
if rows is None:
|
||||
if offset == 0:
|
||||
raise RuntimeError("学时历史没有获取到")
|
||||
return total
|
||||
if not rows:
|
||||
return total
|
||||
add, done = fold_month_minutes(rows, year, month)
|
||||
total += add
|
||||
if done or len(rows) != HISTORY_PAGE_SIZE:
|
||||
return total
|
||||
mark = (
|
||||
len(rows),
|
||||
rows[0].get("studied_at"),
|
||||
rows[0].get("title"),
|
||||
rows[-1].get("studied_at"),
|
||||
rows[-1].get("title"),
|
||||
)
|
||||
if offset == 0:
|
||||
first_mark = mark
|
||||
elif mark == first_mark:
|
||||
return total
|
||||
offset += HISTORY_PAGE_SIZE
|
||||
return total
|
||||
|
||||
|
||||
# ── 单门课程的学习协程 ──
|
||||
|
||||
@@ -480,13 +595,31 @@ class CourseCursor:
|
||||
return item
|
||||
|
||||
|
||||
async def _heartbeat_wait(
|
||||
worker: WorkerView | None,
|
||||
interval: int,
|
||||
stop: asyncio.Event,
|
||||
hours: HoursWatcher,
|
||||
progress: float,
|
||||
) -> bool:
|
||||
delay = _jitter(interval)
|
||||
_touch(worker, interval=interval, heartbeat_at=time.time() + delay, progress=progress, ok=True)
|
||||
return await wait_stop(delay, stop, hours.user_stop)
|
||||
|
||||
|
||||
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||||
worker: WorkerView | None = None) -> None:
|
||||
view = 0
|
||||
started = False
|
||||
while not _halted(stop, hours):
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
schedule = float(progress.get("studyschedule", 0))
|
||||
try:
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
if started:
|
||||
await hours.refresh()
|
||||
@@ -494,29 +627,48 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||||
started = True
|
||||
view = int(progress.get("viewSchedule", view))
|
||||
view += interval
|
||||
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
|
||||
try:
|
||||
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
new_schedule = result.get("studySchedule")
|
||||
if new_schedule is not None and float(new_schedule) >= 100:
|
||||
await hours.refresh()
|
||||
if new_schedule is not None:
|
||||
schedule = _progress_of({"studySchedule": new_schedule})
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
await hours.refresh()
|
||||
return
|
||||
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
|
||||
return
|
||||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||||
|
||||
|
||||
async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
||||
page_size: int, interval: int, stop: asyncio.Event,
|
||||
hours: HoursWatcher) -> None:
|
||||
hours: HoursWatcher, worker: WorkerView | None = None) -> None:
|
||||
view = 1
|
||||
while not _halted(stop, hours):
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
if float(progress.get("studyschedule", 0)) >= 100:
|
||||
try:
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
return
|
||||
try:
|
||||
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
|
||||
return
|
||||
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
|
||||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||||
|
||||
|
||||
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||||
user_id: str, org_id: str) -> None:
|
||||
user_id: str, org_id: str, worker: WorkerView | None = None) -> None:
|
||||
import uuid as _uuid
|
||||
sco_cnt = await session.scorm_count(kid)
|
||||
session_id = str(_uuid.uuid4())
|
||||
@@ -545,28 +697,46 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
||||
return
|
||||
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
|
||||
scorm_data["cmi__core__session_time"] = "00:00:01"
|
||||
await session.scorm_save(
|
||||
session_id=session_id, org_id=org_id, user_id=user_id,
|
||||
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
|
||||
pkg_id=pkg_id, data=scorm_data,
|
||||
)
|
||||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
if float(progress.get("studyschedule", 0)) >= 100:
|
||||
try:
|
||||
await session.scorm_save(
|
||||
session_id=session_id, org_id=org_id, user_id=user_id,
|
||||
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
|
||||
pkg_id=pkg_id, data=scorm_data,
|
||||
)
|
||||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
return
|
||||
if await _heartbeat_wait(worker, min(interval, 5), stop, hours, schedule):
|
||||
return
|
||||
await wait_stop(_jitter(min(interval, 5)), stop, hours.user_stop)
|
||||
|
||||
while not _halted(stop, hours):
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
if float(progress.get("studyschedule", 0)) >= 100:
|
||||
try:
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
return
|
||||
try:
|
||||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
|
||||
return
|
||||
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
|
||||
await wait_stop(_jitter(interval), stop, hours.user_stop)
|
||||
|
||||
|
||||
async def _study_package(session: StudySession, kid: str, intervals: dict,
|
||||
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
|
||||
user_id: str, org_id: str) -> None:
|
||||
user_id: str, org_id: str, worker: WorkerView | None = None) -> None:
|
||||
pkg = await session.sync_package(kid)
|
||||
chapters = pkg.get("userKnowledgeList") or []
|
||||
for ch in chapters:
|
||||
@@ -579,6 +749,7 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
|
||||
if not ch_kid:
|
||||
continue
|
||||
_set_user_status(session._employee_id, course=ch_title)
|
||||
_touch(worker, course=ch_title, progress=_progress_of(ch), ok=True)
|
||||
|
||||
is_video = "Video" in str(ch.get("knowledgeType") or "")
|
||||
ch_type = "video" if is_video else "document"
|
||||
@@ -595,9 +766,9 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
|
||||
pass
|
||||
|
||||
if is_video:
|
||||
await _study_video(session, ch_kid, kid, ch_interval, stop, hours)
|
||||
await _study_video(session, ch_kid, kid, ch_interval, stop, hours, worker)
|
||||
else:
|
||||
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours)
|
||||
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours, worker)
|
||||
|
||||
|
||||
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
|
||||
@@ -693,11 +864,12 @@ class AutoStudyWorker:
|
||||
|
||||
async def _run_cycle(self) -> None:
|
||||
assert self._async_stop is not None
|
||||
from admin.settings import heartbeat_intervals
|
||||
from admin.settings import heartbeat_intervals, hours_source_of
|
||||
from euniv.crypto import decrypt_secret
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
intervals_cfg = heartbeat_intervals()
|
||||
hours_source = hours_source_of()
|
||||
auto_mode = intervals_cfg["mode"] == "auto"
|
||||
intervals = {
|
||||
"video": intervals_cfg["video"],
|
||||
@@ -724,9 +896,10 @@ class AutoStudyWorker:
|
||||
else:
|
||||
waiting += 1
|
||||
continue
|
||||
target = row.monthly_target or 600
|
||||
target = int(row.monthly_target) if row.monthly_target is not None else 600
|
||||
current = _parse_minutes(row.month_hours)
|
||||
if target > 0 and current < target:
|
||||
below = hours_source == "history" or (target > 0 and current < target)
|
||||
if below:
|
||||
try:
|
||||
password = decrypt_secret(row.password_cipher)
|
||||
credential = json.loads(decrypt_secret(row.credential_cipher))
|
||||
@@ -764,7 +937,7 @@ class AutoStudyWorker:
|
||||
tasks = [
|
||||
self._study_user(
|
||||
emp_id, target, pw, cred, proxy, workers, use_pool,
|
||||
course_list, intervals, auto_mode, sem,
|
||||
course_list, intervals, auto_mode, hours_source, sem,
|
||||
)
|
||||
for emp_id, target, pw, cred, proxy, workers, use_pool in eligible
|
||||
]
|
||||
@@ -779,7 +952,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, intervals: dict,
|
||||
auto_mode: bool, sem: asyncio.Semaphore) -> None:
|
||||
auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
user_stop = asyncio.Event()
|
||||
with _halt_lock:
|
||||
@@ -792,7 +965,7 @@ class AutoStudyWorker:
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
_set_user_status(employee_id, state="准备", course="")
|
||||
_set_user_status(employee_id, state="准备", course="", workers={})
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
|
||||
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
|
||||
@@ -805,7 +978,7 @@ class AutoStudyWorker:
|
||||
) as session:
|
||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
||||
_set_user_status(employee_id, state="学习中")
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop)
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
|
||||
if await hours.refresh():
|
||||
return
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
@@ -835,22 +1008,26 @@ class AutoStudyWorker:
|
||||
cursor = CourseCursor(course_list)
|
||||
count = max(1, min(8, int(workers or 1)))
|
||||
|
||||
async def worker() -> None:
|
||||
async def worker_loop(index: int) -> None:
|
||||
view = WorkerView(employee_id, index)
|
||||
view.update(course="", progress=0, interval=0, heartbeat_at=0, ok=True)
|
||||
while not _halted(self._async_stop, hours):
|
||||
item = await cursor.take()
|
||||
if item is None:
|
||||
view.update(course="", progress=100, interval=0, heartbeat_at=0, ok=True)
|
||||
return
|
||||
path, title, kind = item
|
||||
await self._study_one_course(
|
||||
session, employee_id, path, title, kind,
|
||||
intervals, auto_mode, hours, user_id, org_id)
|
||||
intervals, auto_mode, hours, user_id, org_id, view)
|
||||
|
||||
await asyncio.gather(*(worker() for _ in range(count)))
|
||||
await asyncio.gather(*(worker_loop(index) for index in range(1, count + 1)))
|
||||
|
||||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||||
path: str, title: str, kind: str,
|
||||
intervals: dict, auto_mode: bool,
|
||||
hours: HoursWatcher, user_id: str, org_id: str) -> None:
|
||||
hours: HoursWatcher, user_id: str, org_id: str,
|
||||
worker: WorkerView | None = None) -> None:
|
||||
assert self._async_stop is not None
|
||||
if _halted(self._async_stop, hours):
|
||||
return
|
||||
@@ -862,14 +1039,17 @@ class AutoStudyWorker:
|
||||
return
|
||||
|
||||
_set_user_status(employee_id, course=title)
|
||||
_touch(worker, course=title, progress=0, ok=True)
|
||||
|
||||
try:
|
||||
if ctype == "package":
|
||||
await _study_package(session, kid, intervals, auto_mode,
|
||||
self._async_stop, hours, user_id, org_id)
|
||||
self._async_stop, hours, user_id, org_id, worker)
|
||||
else:
|
||||
progress = await session.update_progress(kid, "")
|
||||
if float(progress.get("studyschedule", 0)) >= 100:
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if schedule >= 100:
|
||||
return
|
||||
|
||||
interval = intervals.get(ctype, 120)
|
||||
@@ -886,17 +1066,19 @@ class AutoStudyWorker:
|
||||
pass
|
||||
|
||||
if ctype == "video":
|
||||
await _study_video(session, kid, "", interval, self._async_stop, hours)
|
||||
await _study_video(session, kid, "", interval, self._async_stop, hours, worker)
|
||||
elif ctype == "document":
|
||||
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours)
|
||||
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours, worker)
|
||||
elif ctype == "scorm":
|
||||
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
|
||||
user_id, org_id)
|
||||
user_id, org_id, worker)
|
||||
except SessionExpired:
|
||||
hours.user_stop.set()
|
||||
_touch(worker, ok=False)
|
||||
_set_user_status(employee_id, state="会话过期")
|
||||
log.info("用户 %s 会话过期", employee_id)
|
||||
except Exception as exc:
|
||||
_touch(worker, ok=False)
|
||||
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
||||
|
||||
|
||||
|
||||
+134
-17
@@ -155,6 +155,117 @@ def _history_api_item(row: object) -> dict | None:
|
||||
}
|
||||
|
||||
|
||||
HISTORY_PAGE_SIZE = 100
|
||||
|
||||
|
||||
def history_search_body(pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE) -> dict:
|
||||
body: dict = {"pageable": pageable}
|
||||
if pageable:
|
||||
page = offset // limit + 1 if limit else 1
|
||||
body.update(
|
||||
{
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"page": page,
|
||||
"pageSize": limit,
|
||||
"start": offset,
|
||||
"length": limit,
|
||||
}
|
||||
)
|
||||
return body
|
||||
|
||||
|
||||
def history_items_from_payload(payload: object) -> list[dict] | None:
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
rows = payload.get("datas")
|
||||
if rows is None:
|
||||
rows = payload.get("data")
|
||||
if isinstance(rows, dict):
|
||||
rows = rows.get("datas") or rows.get("list") or rows.get("records") or rows.get("items")
|
||||
if not isinstance(rows, list):
|
||||
return None
|
||||
items = []
|
||||
for row in rows:
|
||||
item = _history_api_item(row)
|
||||
if item is not None:
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def history_stamp(studied_at: str) -> datetime | None:
|
||||
text = (studied_at or "").strip().replace("T", " ")
|
||||
if not text:
|
||||
return None
|
||||
text = text[:19]
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def history_month_side(studied_at: str, year: int, month: int) -> str:
|
||||
stamp = history_stamp(studied_at)
|
||||
if stamp is None:
|
||||
return "unknown"
|
||||
if (stamp.year, stamp.month) == (year, month):
|
||||
return "in"
|
||||
if (stamp.year, stamp.month) < (year, month):
|
||||
return "before"
|
||||
return "after"
|
||||
|
||||
|
||||
def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, bool]:
|
||||
total = 0
|
||||
reached_before = False
|
||||
for item in items:
|
||||
side = history_month_side(str(item.get("studied_at") or ""), year, month)
|
||||
if side == "in":
|
||||
minutes = item.get("minutes")
|
||||
if isinstance(minutes, int):
|
||||
total += minutes
|
||||
elif side == "before":
|
||||
reached_before = True
|
||||
break
|
||||
return total, reached_before
|
||||
|
||||
|
||||
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int:
|
||||
"""倒序分页累加本月分钟,遇到上个月即停。"""
|
||||
offset = 0
|
||||
total = 0
|
||||
first_mark: tuple | None = None
|
||||
for _ in range(50):
|
||||
rows = fetch_page(offset, page_size)
|
||||
if rows is None:
|
||||
if offset == 0:
|
||||
raise RuntimeError("学时历史没有获取到")
|
||||
return total
|
||||
if not rows:
|
||||
return total
|
||||
add, done = fold_month_minutes(rows, year, month)
|
||||
total += add
|
||||
if done:
|
||||
return total
|
||||
if len(rows) != page_size:
|
||||
return total
|
||||
mark = (
|
||||
len(rows),
|
||||
rows[0].get("studied_at"),
|
||||
rows[0].get("title"),
|
||||
rows[-1].get("studied_at"),
|
||||
rows[-1].get("title"),
|
||||
)
|
||||
if offset == 0:
|
||||
first_mark = mark
|
||||
elif mark == first_mark:
|
||||
return total
|
||||
offset += page_size
|
||||
return total
|
||||
|
||||
|
||||
def parse_training_cards(page: str, status: str) -> list[dict]:
|
||||
items = []
|
||||
for block in re.findall(r"<li class='el-plan-li-3'[\s\S]*?</li>", page):
|
||||
@@ -798,33 +909,39 @@ class EunivClient:
|
||||
def study_history(self) -> list[dict]:
|
||||
"""读取「我的学时」列表:来源、获得学时(分钟)、日期。"""
|
||||
try:
|
||||
items = self._study_history_api()
|
||||
items = self._study_history_search(pageable=False)
|
||||
except Exception:
|
||||
items = None
|
||||
if items is not None:
|
||||
return items
|
||||
return self._study_history_page()
|
||||
|
||||
def _study_history_api(self) -> list[dict] | None:
|
||||
def month_history_minutes(self, now: datetime | None = None) -> int:
|
||||
"""倒序分页统计本月学时分钟,遇到上个月即停。"""
|
||||
from euniv.study_window import CN_TZ
|
||||
|
||||
current = now or datetime.now(CN_TZ)
|
||||
year, month = current.year, current.month
|
||||
|
||||
def fetch_page(offset: int, limit: int) -> list[dict] | None:
|
||||
return self._study_history_search(pageable=True, offset=offset, limit=limit)
|
||||
|
||||
try:
|
||||
return accumulate_month_minutes(fetch_page, year, month)
|
||||
except Exception:
|
||||
items = self.study_history()
|
||||
total, _ = fold_month_minutes(items, year, month)
|
||||
return total
|
||||
|
||||
def _study_history_search(
|
||||
self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE
|
||||
) -> list[dict] | None:
|
||||
response = self._request(
|
||||
"POST",
|
||||
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
|
||||
json={"pageable": False},
|
||||
json=history_search_body(pageable, offset, limit),
|
||||
)
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
rows = payload.get("datas")
|
||||
if rows is None:
|
||||
rows = payload.get("data")
|
||||
if not isinstance(rows, list):
|
||||
return None
|
||||
items = []
|
||||
for row in rows:
|
||||
item = _history_api_item(row)
|
||||
if item is not None:
|
||||
items.append(item)
|
||||
return items
|
||||
return history_items_from_payload(response.json())
|
||||
|
||||
def _study_history_page(self) -> list[dict]:
|
||||
text = self._study_period_page()
|
||||
|
||||
@@ -642,7 +642,9 @@ def test_settings_do_not_expose_process_switches() -> None:
|
||||
"heartbeat_video_seconds",
|
||||
"heartbeat_document_seconds",
|
||||
"heartbeat_scorm_seconds",
|
||||
"hours_source",
|
||||
}
|
||||
assert body["hours_source"] == "api"
|
||||
assert identity.password_cipher()
|
||||
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
|
||||
|
||||
@@ -852,3 +854,16 @@ def test_admin_can_save_study_settings_in_one_request() -> None:
|
||||
assert one["study_start"] == "每月8日 09:10:11"
|
||||
assert one["course_workers"] == 2
|
||||
assert one["proxy"] == "HTTP 10.0.0.8:8080"
|
||||
|
||||
|
||||
def test_admin_can_switch_hours_source() -> None:
|
||||
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/settings", json=_settings_body(hours_source="history"))
|
||||
assert saved.status_code == 200
|
||||
assert saved.json()["hours_source"] == "history"
|
||||
assert client.get("/api/admin/settings").json()["hours_source"] == "history"
|
||||
bad = client.put("/api/admin/settings", json=_settings_body(hours_source="other"))
|
||||
assert bad.status_code == 400
|
||||
assert bad.json()["detail"] == "学时达标依据须为 api 或 history"
|
||||
|
||||
@@ -562,11 +562,13 @@ def test_user_can_start_and_stop_study_immediately() -> None:
|
||||
client.put("/api/settings/study-start", json={"day": 31, "hour": 23, "minute": 59, "second": 59})
|
||||
idle = client.get("/api/settings/study-control")
|
||||
assert idle.status_code == 200
|
||||
assert idle.json()["workers"] == []
|
||||
started = client.post("/api/settings/study-control", json={"action": "start"})
|
||||
assert started.status_code == 200
|
||||
assert started.json()["started"] is True
|
||||
assert started.json()["ignore_window"] is True
|
||||
assert started.json()["paused"] is False
|
||||
assert started.json()["workers"] == []
|
||||
stopped = client.post("/api/settings/study-control", json={"action": "stop"})
|
||||
assert stopped.status_code == 200
|
||||
assert stopped.json()["started"] is False
|
||||
|
||||
@@ -4,7 +4,18 @@ import pytest
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.autostudy import (
|
||||
CourseCursor,
|
||||
HoursWatcher,
|
||||
_clear_user_status,
|
||||
_parse_minutes,
|
||||
_set_user_status,
|
||||
_set_worker_status,
|
||||
_study_video,
|
||||
autostudy_status,
|
||||
wait_stop,
|
||||
)
|
||||
from euniv.client import accumulate_month_minutes, fold_month_minutes
|
||||
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
|
||||
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
|
||||
from euniv.study_control import eligible as study_eligible, start_now, stop_now
|
||||
@@ -81,6 +92,70 @@ def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None:
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
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)))
|
||||
|
||||
class _HistorySession:
|
||||
async def month_history_minutes(self) -> int:
|
||||
return 600
|
||||
|
||||
async def month_hours_text(self) -> str:
|
||||
raise AssertionError("history 模式不应读接口本月学时")
|
||||
|
||||
async def main() -> None:
|
||||
user_stop = asyncio.Event()
|
||||
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop, source="history")
|
||||
assert await watcher.refresh() is True
|
||||
assert watcher.reached
|
||||
assert saved == [("u1", "600")]
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
def test_accumulate_month_minutes_stops_at_previous_month() -> None:
|
||||
pages = [
|
||||
[
|
||||
{"title": "a", "minutes": 10, "studied_at": "2026-11-15 09:00:00"},
|
||||
{"title": "b", "minutes": 20, "studied_at": "2026-11-02 09:00:00"},
|
||||
],
|
||||
[
|
||||
{"title": "c", "minutes": 5, "studied_at": "2026-11-01 09:00:00"},
|
||||
{"title": "d", "minutes": 99, "studied_at": "2026-10-31 23:00:00"},
|
||||
{"title": "e", "minutes": 1, "studied_at": "2026-10-01 00:00:00"},
|
||||
],
|
||||
[
|
||||
{"title": "should-not", "minutes": 1000, "studied_at": "2026-09-01 00:00:00"},
|
||||
],
|
||||
]
|
||||
calls: list[tuple[int, int]] = []
|
||||
|
||||
def fetch(offset: int, limit: int):
|
||||
calls.append((offset, limit))
|
||||
return pages[offset // limit]
|
||||
|
||||
assert accumulate_month_minutes(fetch, 2026, 11, page_size=2) == 35
|
||||
assert calls == [(0, 2), (2, 2)]
|
||||
dumped = [
|
||||
{"title": "a", "minutes": 8, "studied_at": "2026-11-14 10:00:00"},
|
||||
{"title": "b", "minutes": 4, "studied_at": "2026-10-30 10:00:00"},
|
||||
]
|
||||
assert fold_month_minutes(dumped, 2026, 11) == (8, True)
|
||||
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == 8
|
||||
|
||||
|
||||
def test_autostudy_status_lists_workers_in_id_order() -> None:
|
||||
_clear_user_status("u1")
|
||||
_set_user_status("u1", state="学习中")
|
||||
_set_worker_status("u1", 2, course="乙", progress=80, ok=True)
|
||||
_set_worker_status("u1", 1, course="甲", progress=10, ok=False)
|
||||
users = autostudy_status()["users"]["u1"]
|
||||
assert [row["id"] for row in users["workers"]] == [1, 2]
|
||||
assert users["workers"][0]["ok"] is False
|
||||
assert users["course"] == "甲"
|
||||
_clear_user_status("u1")
|
||||
|
||||
|
||||
def test_hours_watcher_continues_below_target(monkeypatch) -> None:
|
||||
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui";
|
||||
import { FlashOutline, RefreshOutline } from "@vicons/ionicons5";
|
||||
import { NAlert, NButton, NIcon, NInput, NPagination, NSpin, NTooltip } from "naive-ui";
|
||||
import { RefreshOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface ProxyRow {
|
||||
id: number;
|
||||
@@ -89,6 +89,12 @@ function formatLatency(value: number | null) {
|
||||
return `${value} ms`;
|
||||
}
|
||||
|
||||
const probingHost = computed(() => {
|
||||
if (probingId.value == null) return "";
|
||||
const row = items.value.find((item) => item.id === probingId.value);
|
||||
return row ? `${row.host}:${row.port}` : "";
|
||||
});
|
||||
|
||||
function schemeLabel(value: string) {
|
||||
return value ? value.toUpperCase() : "—";
|
||||
}
|
||||
@@ -261,14 +267,9 @@ onUnmounted(() => stopPoll());
|
||||
</template>
|
||||
立即更新
|
||||
</n-tooltip>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle attr-type="button" :loading="probingAll" :disabled="probingAll || fetching || !items.length" aria-label="测试全部延迟" @click="probeAll">
|
||||
<template #icon><n-icon><FlashOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
测试全部延迟
|
||||
</n-tooltip>
|
||||
<n-button size="small" attr-type="button" :loading="probingAll" :disabled="probingAll || fetching || !items.length" @click="probeAll">
|
||||
测试全部
|
||||
</n-button>
|
||||
<n-input v-model:value="query" placeholder="地址" clearable @clear="search" />
|
||||
<n-button attr-type="submit">搜索</n-button>
|
||||
</form>
|
||||
@@ -287,6 +288,8 @@ onUnmounted(() => stopPoll());
|
||||
</button>
|
||||
</div>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<n-alert v-if="probingAll" class="admin-alert" type="info">正在测试全部代理延迟</n-alert>
|
||||
<n-alert v-else-if="probingId != null" class="admin-alert" type="info">正在测试 {{ probingHost }} 延迟</n-alert>
|
||||
<div class="admin-scroll">
|
||||
<p v-if="loading" class="admin-status">正在获取</p>
|
||||
<p v-else-if="fetching && !items.length" class="admin-status">正在获取</p>
|
||||
@@ -314,26 +317,23 @@ onUnmounted(() => stopPoll());
|
||||
<td>{{ schemeLabel(row.scheme) }}</td>
|
||||
<td>{{ row.anonymity }}</td>
|
||||
<td>{{ row.source }}</td>
|
||||
<td class="when">{{ formatLatency(row.latency_ms) }}</td>
|
||||
<td class="when">
|
||||
<span v-if="probingAll || probingId === row.id" class="probe-loading">
|
||||
<n-spin :size="14" />测试中
|
||||
</span>
|
||||
<template v-else>{{ formatLatency(row.latency_ms) }}</template>
|
||||
</td>
|
||||
<td :class="statusClass(row)">{{ row.status_text }}</td>
|
||||
<td class="when">{{ formatTime(row.last_checked_at) || "—" }}</td>
|
||||
<td>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button
|
||||
size="small"
|
||||
quaternary
|
||||
circle
|
||||
:loading="probingId === row.id"
|
||||
:disabled="probingAll || fetching || (probingId != null && probingId !== row.id)"
|
||||
:aria-label="`测试 ${row.host} 延迟`"
|
||||
@click="probeOne(row)"
|
||||
>
|
||||
<template #icon><n-icon><FlashOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
测试延迟
|
||||
</n-tooltip>
|
||||
<n-button
|
||||
size="tiny"
|
||||
:loading="probingId === row.id"
|
||||
:disabled="probingAll || fetching || (probingId != null && probingId !== row.id)"
|
||||
@click="probeOne(row)"
|
||||
>
|
||||
测试
|
||||
</n-button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -20,6 +20,7 @@ const hbMode = ref("manual");
|
||||
const hbVideo = ref<number | null>(30);
|
||||
const hbDocument = ref<number | null>(120);
|
||||
const hbScorm = ref<number | null>(120);
|
||||
const hoursSource = ref("api");
|
||||
|
||||
const preferenceLabel = computed(() =>
|
||||
showManualJigsaw.value ? "默认勾选手动滑动验证码" : "先尝试自动滑动验证码",
|
||||
@@ -66,6 +67,7 @@ onMounted(async () => {
|
||||
hbVideo.value = readNumber(body.heartbeat_video_seconds) ?? 30;
|
||||
hbDocument.value = readNumber(body.heartbeat_document_seconds) ?? 120;
|
||||
hbScorm.value = readNumber(body.heartbeat_scorm_seconds) ?? 120;
|
||||
hoursSource.value = body.hours_source === "history" ? "history" : "api";
|
||||
loaded.value = true;
|
||||
} catch {
|
||||
errorText.value = "系统配置没有获取到。";
|
||||
@@ -119,6 +121,7 @@ async function save() {
|
||||
heartbeat_video_seconds: hbVideo.value as number,
|
||||
heartbeat_document_seconds: hbDocument.value as number,
|
||||
heartbeat_scorm_seconds: hbScorm.value as number,
|
||||
hours_source: hoursSource.value,
|
||||
};
|
||||
if (password.value !== "" || confirmPassword.value !== "") {
|
||||
if (password.value !== confirmPassword.value) {
|
||||
@@ -218,6 +221,18 @@ async function save() {
|
||||
</template>
|
||||
</n-form>
|
||||
</section>
|
||||
<section class="panel-card">
|
||||
<h3>学时达标</h3>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="176" :show-feedback="false" size="small">
|
||||
<n-form-item label="判断依据">
|
||||
<n-radio-group v-model:value="hoursSource" size="small">
|
||||
<n-radio-button value="api">接口本月学时</n-radio-button>
|
||||
<n-radio-button value="history">学时历史统计</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<p class="form-hint">学时历史按倒序分页统计到上个月为止</p>
|
||||
</section>
|
||||
<section class="panel-card">
|
||||
<h3>管理员</h3>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="176" :show-feedback="false" size="small">
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, HelpCircleOutline, PauseOutline, PlayOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, SettingsOutline, WarningOutline } from "@vicons/ionicons5";
|
||||
import { dayOptions, workerOptions } from "../../shared/studyFields";
|
||||
|
||||
interface UserRow {
|
||||
employee_id: string;
|
||||
@@ -704,62 +705,51 @@ onMounted(() => {
|
||||
@update:show="(show) => (settingsOpen = show)"
|
||||
>
|
||||
<n-alert v-if="settingsError" class="admin-alert" type="error">{{ settingsError }}</n-alert>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="88" :show-feedback="false" size="small" @submit.prevent="saveSettings">
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small" @submit.prevent="saveSettings">
|
||||
<n-form-item label="每月目标">
|
||||
<div class="target-control">
|
||||
<n-input-number id="admin-monthly-target" v-model:value="monthlyTarget" button-placement="both" :min="0" :max="9999" :precision="0" />
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item label="每月开始">
|
||||
<n-form-item label="定时启动">
|
||||
<div class="target-control start-control">
|
||||
<n-input-number id="admin-start-day" v-model:value="startDay" button-placement="both" :min="1" :max="31" :precision="0" />
|
||||
<span class="target-unit">日</span>
|
||||
<n-select id="admin-start-day" v-model:value="startDay" :options="dayOptions" class="day-select" />
|
||||
<n-tooltip v-if="startDay === 1" placement="top">
|
||||
<template #trigger>
|
||||
<n-icon class="day-warn"><WarningOutline /></n-icon>
|
||||
</template>
|
||||
不推荐使用
|
||||
</n-tooltip>
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" />
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<template #label>
|
||||
<span class="field-title">
|
||||
<span>同时课程</span>
|
||||
<n-tooltip placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</span>
|
||||
</template>
|
||||
<div class="target-control">
|
||||
<n-input-number id="admin-course-workers" v-model:value="workersValue" button-placement="both" :min="1" :max="8" :precision="0" />
|
||||
<span class="target-unit">门</span>
|
||||
<span v-if="workersValue === 1" class="recommend-mark">推荐</span>
|
||||
</div>
|
||||
<n-form-item label="线程数量">
|
||||
<n-select id="admin-course-workers" v-model:value="workersValue" :options="workerOptions" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理类型">
|
||||
<n-select v-model:value="proxyScheme" :options="proxyOptions" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理地址">
|
||||
<n-input v-model:value="proxyHost" placeholder="例如 127.0.0.1" :disabled="!proxyManual" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理端口">
|
||||
<n-input-number v-model:value="proxyPort" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="!proxyManual" placeholder="请输入" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理账号">
|
||||
<n-input v-model:value="proxyUser" placeholder="可不填" autocomplete="off" :disabled="!proxyManual" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理密码">
|
||||
<n-input
|
||||
v-model:value="proxyPassword"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="settingsIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
:disabled="!proxyManual"
|
||||
/>
|
||||
</n-form-item>
|
||||
<template v-if="proxyManual">
|
||||
<n-form-item label="代理地址">
|
||||
<n-input v-model:value="proxyHost" placeholder="例如 127.0.0.1" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理端口">
|
||||
<n-input-number v-model:value="proxyPort" button-placement="both" :min="1" :max="65535" :precision="0" placeholder="请输入" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理账号">
|
||||
<n-input v-model:value="proxyUser" placeholder="可不填" autocomplete="off" />
|
||||
</n-form-item>
|
||||
<n-form-item label="代理密码">
|
||||
<n-input
|
||||
v-model:value="proxyPassword"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="settingsIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</n-form-item>
|
||||
</template>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
|
||||
@@ -86,6 +86,45 @@ function refresh() {
|
||||
});
|
||||
}
|
||||
|
||||
function beijingParts(now = new Date()) {
|
||||
const fmt = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Asia/Shanghai",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
const mapped = Object.fromEntries(fmt.formatToParts(now).map((part) => [part.type, part.value]));
|
||||
return { y: Number(mapped.year), m: Number(mapped.month), d: Number(mapped.day) };
|
||||
}
|
||||
|
||||
function stampParts(text: string) {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(text.trim());
|
||||
if (!match) return null;
|
||||
return { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) };
|
||||
}
|
||||
|
||||
function sumMinutes(filter: (stamp: { y: number; m: number; d: number }) => boolean) {
|
||||
const rows = items.value ?? [];
|
||||
let total = 0;
|
||||
for (const item of rows) {
|
||||
if (typeof item.minutes !== "number") continue;
|
||||
const stamp = stampParts(item.studied_at);
|
||||
if (!stamp) continue;
|
||||
if (filter(stamp)) total += item.minutes;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
const historyFacts = computed(() => {
|
||||
const now = beijingParts();
|
||||
return [
|
||||
{ label: "总学时", value: sumMinutes(() => true) },
|
||||
{ label: "本年学时", value: sumMinutes((stamp) => stamp.y === now.y) },
|
||||
{ label: "本月学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m) },
|
||||
{ label: "本日学时", value: sumMinutes((stamp) => stamp.y === now.y && stamp.m === now.m && stamp.d === now.d) },
|
||||
];
|
||||
});
|
||||
|
||||
const paged = computed(() => {
|
||||
const rows = items.value ?? [];
|
||||
const start = (page.value - 1) * pageSize.value;
|
||||
@@ -157,6 +196,15 @@ onMounted(refresh);
|
||||
</n-tooltip>
|
||||
</header>
|
||||
<n-alert v-if="state === 'error'" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<dl class="facts history-facts">
|
||||
<div v-for="item in historyFacts" :key="item.label">
|
||||
<dt>{{ item.label }}</dt>
|
||||
<dd>
|
||||
<span v-if="state === 'loading'" class="bone bone-value"></span>
|
||||
<template v-else>{{ state === "ready" ? item.value : "—" }}</template>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div class="history-table">
|
||||
<n-data-table
|
||||
v-if="state !== 'error'"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NSelect, NTimePicker, NTooltip } from "naive-ui";
|
||||
import { HelpCircleOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NModal, NProgress, NSelect, NTimePicker, NTooltip } from "naive-ui";
|
||||
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline, WarningOutline } from "@vicons/ionicons5";
|
||||
import { dayOptions, workerOptions } from "../../shared/studyFields";
|
||||
|
||||
interface HomeSummary {
|
||||
name: string;
|
||||
@@ -16,6 +17,15 @@ interface HomeSummary {
|
||||
points: string | number | null;
|
||||
}
|
||||
|
||||
interface StudyWorker {
|
||||
id: number;
|
||||
course: string;
|
||||
progress: number;
|
||||
interval: number;
|
||||
heartbeat_at: number;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
type SectionState = "loading" | "ready" | "error";
|
||||
|
||||
const props = defineProps<{ employeeId: string }>();
|
||||
@@ -25,22 +35,13 @@ const summaryError = ref("");
|
||||
const refreshing = ref(false);
|
||||
let refreshRunning = false;
|
||||
let busy = false;
|
||||
let studyPoll = 0;
|
||||
const nowTick = ref(Date.now());
|
||||
|
||||
const monthlyTarget = ref<number | null>(null);
|
||||
const targetLoaded = ref(false);
|
||||
let targetSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
interface StudyUserState {
|
||||
state?: string;
|
||||
course?: string;
|
||||
}
|
||||
|
||||
const studyStatus = ref<{
|
||||
running: boolean;
|
||||
users?: Record<string, StudyUserState>;
|
||||
message: string;
|
||||
} | null>(null);
|
||||
|
||||
const studyControl = ref({
|
||||
started: false,
|
||||
paused: false,
|
||||
@@ -49,28 +50,22 @@ const studyControl = ref({
|
||||
active: false,
|
||||
state: "",
|
||||
course: "",
|
||||
message: "",
|
||||
workers: [] as StudyWorker[],
|
||||
});
|
||||
const studyBusy = ref(false);
|
||||
const studyError = ref("");
|
||||
|
||||
const myStudy = computed(() => {
|
||||
const users = studyStatus.value?.users;
|
||||
if (!users) return null;
|
||||
return users[props.employeeId] ?? null;
|
||||
});
|
||||
|
||||
const studyLabel = computed(() => {
|
||||
const live = myStudy.value;
|
||||
const state = live?.state || studyControl.value.state;
|
||||
const course = live?.course || studyControl.value.course;
|
||||
const state = studyControl.value.state;
|
||||
const course = studyControl.value.course;
|
||||
if (state === "已达标") return "本月目标已达到";
|
||||
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
|
||||
if (studyControl.value.active || live) {
|
||||
if (studyControl.value.active) {
|
||||
return `正在学习:${course || state || "准备中"}`;
|
||||
}
|
||||
if (studyControl.value.started) return "任务已开始,等待执行";
|
||||
if (studyStatus.value?.message) return studyStatus.value.message;
|
||||
if (studyStatus.value?.running) return "自动学习进行中";
|
||||
if (studyControl.value.message) return studyControl.value.message;
|
||||
return "未到开始时间";
|
||||
});
|
||||
|
||||
@@ -102,6 +97,41 @@ function pad(value: number) {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
function asWorkers(value: unknown): StudyWorker[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const rows: StudyWorker[] = [];
|
||||
for (const item of value) {
|
||||
if (!item || typeof item !== "object") continue;
|
||||
const row = item as Record<string, unknown>;
|
||||
rows.push({
|
||||
id: typeof row.id === "number" ? row.id : rows.length + 1,
|
||||
course: typeof row.course === "string" ? row.course : "",
|
||||
progress: typeof row.progress === "number" ? row.progress : 0,
|
||||
interval: typeof row.interval === "number" ? row.interval : 0,
|
||||
heartbeat_at: typeof row.heartbeat_at === "number" ? row.heartbeat_at : 0,
|
||||
ok: row.ok !== false,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function workerPercent(row: StudyWorker) {
|
||||
return Math.min(100, Math.max(0, Math.round(row.progress)));
|
||||
}
|
||||
|
||||
function workerTitle(row: StudyWorker) {
|
||||
if (row.course) return row.course;
|
||||
if (workerPercent(row) >= 100) return "空闲";
|
||||
return "准备";
|
||||
}
|
||||
|
||||
function heartbeatLeft(row: StudyWorker) {
|
||||
void nowTick.value;
|
||||
if (!row.heartbeat_at) return "—";
|
||||
const left = Math.max(0, Math.ceil(row.heartbeat_at - Date.now() / 1000));
|
||||
return `${left}s`;
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
@@ -134,7 +164,7 @@ function refresh() {
|
||||
if (refreshRunning) return;
|
||||
refreshRunning = true;
|
||||
refreshing.value = true;
|
||||
void Promise.all([loadSummary(), loadStudyStatus(), loadStudyControl()]).finally(() => {
|
||||
void Promise.all([loadSummary(), loadStudyControl()]).finally(() => {
|
||||
refreshRunning = false;
|
||||
refreshing.value = false;
|
||||
});
|
||||
@@ -256,6 +286,7 @@ function saveWorkers(value: number | null) {
|
||||
|
||||
watch(courseWorkers, (v) => { if (workersLoaded.value) saveWorkers(v); });
|
||||
|
||||
const proxyOpen = ref(false);
|
||||
const proxyLoaded = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
@@ -266,6 +297,31 @@ const proxyUser = ref("");
|
||||
const proxyPassword = ref("");
|
||||
const proxyHasPassword = ref(false);
|
||||
const proxyManual = computed(() => proxyScheme.value !== "off" && proxyScheme.value !== "pool");
|
||||
const savedProxy = {
|
||||
scheme: "off",
|
||||
host: "",
|
||||
port: null as number | null,
|
||||
username: "",
|
||||
hasPassword: false,
|
||||
};
|
||||
|
||||
function rememberProxy() {
|
||||
savedProxy.scheme = proxyScheme.value;
|
||||
savedProxy.host = proxyHost.value;
|
||||
savedProxy.port = proxyPort.value;
|
||||
savedProxy.username = proxyUser.value;
|
||||
savedProxy.hasPassword = proxyHasPassword.value;
|
||||
}
|
||||
|
||||
function restoreProxy() {
|
||||
proxyScheme.value = savedProxy.scheme;
|
||||
proxyHost.value = savedProxy.host;
|
||||
proxyPort.value = savedProxy.port;
|
||||
proxyUser.value = savedProxy.username;
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = savedProxy.hasPassword;
|
||||
proxyError.value = "";
|
||||
}
|
||||
const proxyOptions = [
|
||||
{ label: "关闭", value: "off" },
|
||||
{ label: "自动", value: "pool" },
|
||||
@@ -287,6 +343,7 @@ async function loadProxy() {
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = data.has_password === true;
|
||||
proxyLoaded.value = true;
|
||||
rememberProxy();
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
@@ -339,6 +396,8 @@ async function saveProxy() {
|
||||
proxyUser.value = "";
|
||||
proxyHasPassword.value = false;
|
||||
}
|
||||
rememberProxy();
|
||||
proxyOpen.value = false;
|
||||
} catch {
|
||||
proxyError.value = "没有保存。";
|
||||
} finally {
|
||||
@@ -346,13 +405,6 @@ async function saveProxy() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStudyStatus() {
|
||||
try {
|
||||
const res = await fetch("/api/autostudy/status");
|
||||
if (res.ok) studyStatus.value = await res.json();
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function applyStudyControl(payload: Record<string, unknown>) {
|
||||
studyControl.value = {
|
||||
started: payload.started === true,
|
||||
@@ -362,6 +414,8 @@ function applyStudyControl(payload: Record<string, unknown>) {
|
||||
active: payload.active === true,
|
||||
state: typeof payload.state === "string" ? payload.state : "",
|
||||
course: typeof payload.course === "string" ? payload.course : "",
|
||||
message: typeof payload.message === "string" ? payload.message : "",
|
||||
workers: asWorkers(payload.workers),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -373,6 +427,33 @@ async function loadStudyControl() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
function startStudyPoll() {
|
||||
if (studyPoll) return;
|
||||
studyPoll = window.setInterval(() => {
|
||||
nowTick.value = Date.now();
|
||||
void loadStudyControl();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function stopStudyPoll() {
|
||||
if (studyPoll) {
|
||||
window.clearInterval(studyPoll);
|
||||
studyPoll = 0;
|
||||
}
|
||||
}
|
||||
|
||||
watch(proxyOpen, (open, wasOpen) => {
|
||||
if (wasOpen && !open) restoreProxy();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => studyControl.value.started,
|
||||
(started) => {
|
||||
if (started) startStudyPoll();
|
||||
else stopStudyPoll();
|
||||
},
|
||||
);
|
||||
|
||||
async function toggleStudy() {
|
||||
if (studyBusy.value) return;
|
||||
studyBusy.value = true;
|
||||
@@ -390,7 +471,6 @@ async function toggleStudy() {
|
||||
return;
|
||||
}
|
||||
applyStudyControl(data);
|
||||
await loadStudyStatus();
|
||||
} catch {
|
||||
studyError.value = action === "start" ? "没有开始。" : "没有停止。";
|
||||
} finally {
|
||||
@@ -405,6 +485,13 @@ onMounted(() => {
|
||||
loadWorkers();
|
||||
loadProxy();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
stopStudyPoll();
|
||||
clearTimeout(targetSaveTimer);
|
||||
clearTimeout(startSaveTimer);
|
||||
clearTimeout(workersSaveTimer);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -461,7 +548,7 @@ onMounted(() => {
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="panel-card">
|
||||
<section class="panel-card study-card">
|
||||
<header class="panel-card-head">
|
||||
<h3>自动学习</h3>
|
||||
<n-button
|
||||
@@ -477,7 +564,7 @@ onMounted(() => {
|
||||
</n-button>
|
||||
</header>
|
||||
<n-alert v-if="studyError" class="summary-error" type="error">{{ studyError }}</n-alert>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="88" :show-feedback="false" size="small">
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="96" :show-feedback="false" size="small">
|
||||
<n-form-item v-if="targetLoaded" label="每月目标">
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
@@ -492,66 +579,68 @@ onMounted(() => {
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="startLoaded" label="每月开始">
|
||||
<n-form-item v-if="startLoaded" label="定时启动">
|
||||
<div class="target-control start-control">
|
||||
<n-input-number id="study-start-day" v-model:value="startDay" button-placement="both" :min="1" :max="31" :precision="0" size="small" />
|
||||
<span class="target-unit">日</span>
|
||||
<n-select id="study-start-day" v-model:value="startDay" size="small" :options="dayOptions" class="day-select" />
|
||||
<n-tooltip v-if="startDay === 1" placement="top">
|
||||
<template #trigger>
|
||||
<n-icon class="day-warn"><WarningOutline /></n-icon>
|
||||
</template>
|
||||
不推荐使用
|
||||
</n-tooltip>
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" size="small" :actions="null" />
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="workersLoaded">
|
||||
<template #label>
|
||||
<span class="field-title">
|
||||
<span>同时课程</span>
|
||||
<n-tooltip placement="top">
|
||||
<template #trigger>
|
||||
<button type="button" class="hint-icon" aria-label="说明">
|
||||
<n-icon><HelpCircleOutline /></n-icon>
|
||||
</button>
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</span>
|
||||
</template>
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="course-workers"
|
||||
v-model:value="courseWorkers"
|
||||
button-placement="both"
|
||||
:min="1"
|
||||
:max="8"
|
||||
:precision="0"
|
||||
size="small"
|
||||
/>
|
||||
<span class="target-unit">门</span>
|
||||
<span v-if="courseWorkers === 1" class="recommend-mark">推荐</span>
|
||||
</div>
|
||||
<n-form-item v-if="workersLoaded" label="线程数量">
|
||||
<n-select id="course-workers" v-model:value="courseWorkers" size="small" :options="workerOptions" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<div class="home-study-status">
|
||||
<span class="study-indicator" :class="{ active: studyControl.started || studyControl.active }"></span>
|
||||
<span class="study-text" :class="{ muted: !studyControl.active }">{{ studyLabel }}</span>
|
||||
</div>
|
||||
<ul v-if="studyControl.started && studyControl.workers.length" class="study-workers">
|
||||
<li v-for="row in studyControl.workers" :key="row.id" class="study-worker">
|
||||
<div class="study-worker-main">
|
||||
<span class="study-worker-title">{{ workerTitle(row) }}</span>
|
||||
<n-progress type="line" :percentage="workerPercent(row)" :show-indicator="false" :height="8" />
|
||||
</div>
|
||||
<div class="study-worker-meta">
|
||||
<span class="study-worker-pct">{{ workerPercent(row) }}%</span>
|
||||
<span class="study-heartbeat">{{ heartbeatLeft(row) }}</span>
|
||||
<span class="study-dot" :class="row.ok ? 'up' : 'down'"></span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="study-card-foot">
|
||||
<n-button v-if="proxyLoaded" size="small" quaternary @click="proxyOpen = true">
|
||||
<template #icon><n-icon><GlobeOutline /></n-icon></template>
|
||||
代理
|
||||
</n-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form v-if="proxyLoaded" class="panel-card" @submit.prevent="saveProxy">
|
||||
<header class="panel-card-head">
|
||||
<h3>代理</h3>
|
||||
<n-button type="primary" size="small" attr-type="submit" :loading="proxySaving">保存</n-button>
|
||||
</header>
|
||||
<n-alert v-if="proxyError" class="summary-error" type="error">{{ proxyError }}</n-alert>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="88" :show-feedback="false" size="small">
|
||||
<n-form-item label="类型">
|
||||
<n-select v-model:value="proxyScheme" size="small" :options="proxyOptions" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
<n-modal
|
||||
:show="proxyOpen"
|
||||
preset="card"
|
||||
title="代理"
|
||||
:style="{ width: 'min(420px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (proxyOpen = show)"
|
||||
>
|
||||
<n-alert v-if="proxyError" class="summary-error" type="error">{{ proxyError }}</n-alert>
|
||||
<n-form class="compact-nform" label-placement="left" label-align="left" :label-width="72" :show-feedback="false" size="small">
|
||||
<n-form-item label="类型">
|
||||
<n-select v-model:value="proxyScheme" size="small" :options="proxyOptions" />
|
||||
</n-form-item>
|
||||
<template v-if="proxyManual">
|
||||
<n-form-item label="地址">
|
||||
<n-input v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" :disabled="!proxyManual" />
|
||||
<n-input v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" />
|
||||
</n-form-item>
|
||||
<n-form-item label="端口">
|
||||
<n-input-number v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="!proxyManual" placeholder="请输入" />
|
||||
<n-input-number v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" placeholder="请输入" />
|
||||
</n-form-item>
|
||||
<n-form-item label="账号">
|
||||
<n-input v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" :disabled="!proxyManual" />
|
||||
<n-input v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" />
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input
|
||||
@@ -561,11 +650,16 @@ onMounted(() => {
|
||||
show-password-on="click"
|
||||
:placeholder="proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
:disabled="!proxyManual"
|
||||
/>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="proxyOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="proxySaving" @click="saveProxy">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
export const workerOptions = [
|
||||
{ label: "1 · 推荐,速度较慢,稳定且不容易触发风控", value: 1 },
|
||||
{ label: "2", value: 2 },
|
||||
{ label: "3", value: 3 },
|
||||
{ label: "4", value: 4 },
|
||||
{ label: "5", value: 5 },
|
||||
{ label: "6", value: 6 },
|
||||
{ label: "7", value: 7 },
|
||||
{ label: "8 · 最大", value: 8 },
|
||||
];
|
||||
|
||||
export const dayOptions = Array.from({ length: 31 }, (_, index) => ({
|
||||
label: `${index + 1}日`,
|
||||
value: index + 1,
|
||||
}));
|
||||
@@ -558,10 +558,20 @@ select {
|
||||
width: 88px;
|
||||
}
|
||||
|
||||
.start-control .day-select {
|
||||
width: 108px;
|
||||
}
|
||||
|
||||
.start-control .n-time-picker {
|
||||
width: 148px;
|
||||
}
|
||||
|
||||
.day-warn {
|
||||
color: #d29922;
|
||||
font-size: 18px;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.target-unit {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
@@ -597,6 +607,97 @@ select {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.study-workers {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.study-worker {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.study-worker-main {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.study-worker-title {
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.study-worker-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.study-worker-pct {
|
||||
width: 36px;
|
||||
text-align: right;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.study-heartbeat {
|
||||
width: 36px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.study-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.study-dot.up {
|
||||
background: #3fb950;
|
||||
box-shadow: 0 0 6px rgba(63, 185, 80, 0.5);
|
||||
}
|
||||
|
||||
.study-dot.down {
|
||||
background: #f85149;
|
||||
box-shadow: 0 0 6px rgba(248, 81, 73, 0.5);
|
||||
}
|
||||
|
||||
.study-card-foot {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.history-facts {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
|
||||
.probe-loading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.profile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1022,6 +1123,10 @@ select {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.history-facts {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.detail-facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user