feat: 立即开始停止学习并整理学时历史与界面
This commit is contained in:
@@ -22,11 +22,16 @@ from admin.users import (
|
||||
set_course_workers,
|
||||
set_paused,
|
||||
set_proxy,
|
||||
set_study_action,
|
||||
set_study_settings,
|
||||
set_study_start,
|
||||
)
|
||||
from euniv.courses import course_page, request_course_sync_now
|
||||
from euniv.db import get_db
|
||||
from euniv.proxy_pool import ProxyProbeError
|
||||
from euniv.proxy_pool import page as proxy_page
|
||||
from euniv.proxy_pool import probe_ids as probe_proxy_ids
|
||||
from euniv.proxy_pool import probe_one as probe_proxy_one
|
||||
from euniv.proxy_pool import request_refresh as request_proxy_refresh
|
||||
|
||||
public_router = APIRouter()
|
||||
@@ -76,6 +81,30 @@ class AdminCourseWorkersBody(BaseModel):
|
||||
workers: int
|
||||
|
||||
|
||||
class AdminStudyActionBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
action: str
|
||||
|
||||
|
||||
class AdminStudySettingsBody(BaseModel):
|
||||
employee_ids: list[str]
|
||||
monthly_target: int | None = None
|
||||
day: int | None = None
|
||||
hour: int | None = None
|
||||
minute: int | None = None
|
||||
second: int | None = None
|
||||
workers: int | None = None
|
||||
scheme: str | None = None
|
||||
host: str = ""
|
||||
port: int | None = None
|
||||
username: str = ""
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class AdminProxyProbeBody(BaseModel):
|
||||
ids: list[int] | None = None
|
||||
|
||||
|
||||
def require_admin(request: Request) -> str:
|
||||
if not admin_session_active(request.cookies):
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
@@ -148,6 +177,22 @@ def post_proxies_refresh(_: str = Depends(require_admin)) -> dict:
|
||||
return request_proxy_refresh()
|
||||
|
||||
|
||||
@admin_router.post("/proxies/probe")
|
||||
def post_proxies_probe(body: AdminProxyProbeBody, _: str = Depends(require_admin)) -> dict:
|
||||
try:
|
||||
return probe_proxy_ids(body.ids)
|
||||
except ProxyProbeError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@admin_router.post("/proxies/{proxy_id}/probe")
|
||||
def post_proxy_probe(proxy_id: int, _: str = Depends(require_admin)) -> dict:
|
||||
try:
|
||||
return probe_proxy_one(proxy_id)
|
||||
except ProxyProbeError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@admin_router.get("/users")
|
||||
def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]:
|
||||
return list_users(db)
|
||||
@@ -224,6 +269,34 @@ def get_user_course_workers(employee_id: str, db: Session = Depends(get_db), _:
|
||||
return read_course_workers(db, employee_id)
|
||||
|
||||
|
||||
@admin_router.post("/users/study")
|
||||
def post_users_study(
|
||||
body: AdminStudyActionBody, db: Session = Depends(get_db), _: str = Depends(require_admin)
|
||||
) -> dict:
|
||||
return set_study_action(db, body.employee_ids, body.action)
|
||||
|
||||
|
||||
@admin_router.put("/users/study-settings")
|
||||
def put_users_study_settings(
|
||||
body: AdminStudySettingsBody, db: Session = Depends(get_db), _: str = Depends(require_admin)
|
||||
) -> dict:
|
||||
return set_study_settings(
|
||||
db,
|
||||
body.employee_ids,
|
||||
monthly_target=body.monthly_target,
|
||||
day=body.day,
|
||||
hour=body.hour,
|
||||
minute=body.minute,
|
||||
second=body.second,
|
||||
workers=body.workers,
|
||||
scheme=body.scheme,
|
||||
host=body.host,
|
||||
port=body.port,
|
||||
username=body.username,
|
||||
password=body.password,
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
+69
-3
@@ -16,6 +16,8 @@ from euniv.course_workers import apply as apply_workers
|
||||
from euniv.course_workers import of as workers_of
|
||||
from euniv.course_workers import view_of as workers_view
|
||||
from euniv.proxy import ProxyError, apply, clear, enabled, summary_of, url_of, view_of
|
||||
from euniv.study_control import start_now, stop_now
|
||||
from euniv.study_control import view_of as study_view
|
||||
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
|
||||
@@ -65,7 +67,10 @@ def _iso_time(value: datetime | None) -> str | None:
|
||||
|
||||
def list_users(db: Session) -> list[dict]:
|
||||
accounts = db.scalars(select(Account).order_by(Account.employee_id)).all()
|
||||
return [
|
||||
rows = []
|
||||
for account in accounts:
|
||||
control = study_view(account)
|
||||
rows.append(
|
||||
{
|
||||
"employee_id": account.employee_id,
|
||||
"has_credential": bool(account.credential_cipher),
|
||||
@@ -73,6 +78,7 @@ def list_users(db: Session) -> list[dict]:
|
||||
"last_refresh_at": _iso_time(account.last_refresh_at),
|
||||
"credential_valid": _optional_bool(account.credential_valid),
|
||||
"month_hours": account.month_hours or "",
|
||||
"monthly_target": int(account.monthly_target or 600),
|
||||
"has_proxy": enabled(account),
|
||||
"proxy": summary_of(account),
|
||||
"study_start": start_label(account),
|
||||
@@ -81,9 +87,12 @@ def list_users(db: Session) -> list[dict]:
|
||||
"study_start_minute": int(account.study_start_minute or 0),
|
||||
"study_start_second": int(account.study_start_second or 0),
|
||||
"course_workers": workers_of(account),
|
||||
"study_paused": control["paused"],
|
||||
"study_ignore_window": control["ignore_window"],
|
||||
"study_started": control["started"],
|
||||
}
|
||||
for account in accounts
|
||||
]
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _require(db: Session, employee_id: str) -> Account:
|
||||
@@ -270,6 +279,63 @@ def set_course_workers(db: Session, employee_ids: list[str], workers: int) -> di
|
||||
return {"ok": True, "count": len(accounts)}
|
||||
|
||||
|
||||
def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict:
|
||||
kind = (action or "").strip().lower()
|
||||
if kind not in {"start", "stop"}:
|
||||
raise HTTPException(status_code=400, detail="请选择开始或停止")
|
||||
accounts = _accounts_by_ids(db, employee_ids)
|
||||
from euniv.autostudy import request_stop, request_wake
|
||||
|
||||
for account in accounts:
|
||||
if kind == "start":
|
||||
start_now(account)
|
||||
else:
|
||||
stop_now(account)
|
||||
db.commit()
|
||||
if kind == "start":
|
||||
request_wake()
|
||||
else:
|
||||
for account in accounts:
|
||||
request_stop(account.employee_id)
|
||||
return {"ok": True, "count": len(accounts), "action": kind}
|
||||
|
||||
|
||||
def set_study_settings(
|
||||
db: Session,
|
||||
employee_ids: list[str],
|
||||
monthly_target: int | None = None,
|
||||
day: int | None = None,
|
||||
hour: int | None = None,
|
||||
minute: int | None = None,
|
||||
second: int | None = None,
|
||||
workers: int | None = None,
|
||||
scheme: str | None = None,
|
||||
host: str = "",
|
||||
port: object = None,
|
||||
username: str = "",
|
||||
password: str | None = None,
|
||||
) -> dict:
|
||||
accounts = _accounts_by_ids(db, employee_ids)
|
||||
if monthly_target is not None:
|
||||
if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999:
|
||||
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
|
||||
try:
|
||||
for account in accounts:
|
||||
if monthly_target is not None:
|
||||
account.monthly_target = monthly_target
|
||||
if day is not None:
|
||||
apply_start(account, day, hour, minute, second)
|
||||
if workers is not None:
|
||||
apply_workers(account, workers)
|
||||
if scheme is not None:
|
||||
apply(account, scheme, host, port, username, password)
|
||||
except (StudyWindowError, CourseWorkersError, ProxyError) 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)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""账号自动学习启停:暂停标记与立即开始(忽略开始时刻)。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0012_study_control"
|
||||
down_revision = "0011_proxy_pool"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.add_column(
|
||||
sa.Column("study_paused", sa.Boolean(), nullable=False, server_default=sa.false())
|
||||
)
|
||||
batch.add_column(
|
||||
sa.Column("study_ignore_window", sa.Boolean(), nullable=False, server_default=sa.false())
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("accounts") as batch:
|
||||
batch.drop_column("study_ignore_window")
|
||||
batch.drop_column("study_paused")
|
||||
@@ -23,6 +23,7 @@ from euniv.service import (
|
||||
fetch_home_exams,
|
||||
fetch_home_summary,
|
||||
fetch_home_trainings,
|
||||
fetch_study_history,
|
||||
fetch_training_detail,
|
||||
login_and_store,
|
||||
revoke_credential,
|
||||
@@ -57,6 +58,10 @@ class CourseWorkersBody(_BaseModel):
|
||||
workers: int
|
||||
|
||||
|
||||
class StudyControlBody(_BaseModel):
|
||||
action: str
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
@@ -336,6 +341,56 @@ def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
return autostudy_status()
|
||||
|
||||
|
||||
@app.get("/api/settings/study-control")
|
||||
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.autostudy import autostudy_status
|
||||
from euniv.study_control import view_of
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
payload = view_of(account)
|
||||
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["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
|
||||
if payload["active"]:
|
||||
payload["started"] = True
|
||||
return payload
|
||||
|
||||
|
||||
@app.post("/api/settings/study-control")
|
||||
def post_study_control(body: StudyControlBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.autostudy import request_stop, request_wake
|
||||
from euniv.study_control import start_now, stop_now
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
action = (body.action or "").strip().lower()
|
||||
if action == "start":
|
||||
start_now(account)
|
||||
db.commit()
|
||||
request_wake()
|
||||
elif action == "stop":
|
||||
stop_now(account)
|
||||
db.commit()
|
||||
request_stop(employee_id)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="请选择开始或停止")
|
||||
return get_study_control(request, db)
|
||||
|
||||
|
||||
@app.get("/api/home/history")
|
||||
def home_history(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
return fetch_study_history(db, _signed_in(request, db))
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/training")
|
||||
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
|
||||
+60
-11
@@ -28,7 +28,7 @@ from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpir
|
||||
from euniv.course_workers import of as course_workers_of
|
||||
from euniv.models import Account, Course
|
||||
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
|
||||
from euniv.study_window import window_open
|
||||
from euniv.study_control import eligible as study_eligible
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -37,6 +37,9 @@ _HOURS_REFRESH_SECONDS = 300.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
|
||||
_halt_lock = threading.Lock()
|
||||
_user_halts: dict[str, asyncio.Event] = {}
|
||||
_worker = None
|
||||
|
||||
|
||||
def autostudy_status() -> dict:
|
||||
@@ -63,6 +66,30 @@ def _clear_user_status(employee_id: str) -> None:
|
||||
_status.get("users", {}).pop(employee_id, None)
|
||||
|
||||
|
||||
def request_stop(employee_id: str) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return
|
||||
with _halt_lock:
|
||||
event = _user_halts.get(key)
|
||||
if event is not None:
|
||||
event.set()
|
||||
_set_user_status(key, state="已停止", course="")
|
||||
|
||||
|
||||
def request_wake() -> None:
|
||||
worker = _worker
|
||||
if worker is not None:
|
||||
worker.wake()
|
||||
|
||||
|
||||
def is_studying(employee_id: str) -> bool:
|
||||
key = (employee_id or "").strip()
|
||||
with _halt_lock:
|
||||
event = _user_halts.get(key)
|
||||
return event is not None and not event.is_set()
|
||||
|
||||
|
||||
# ── 课程路径解析 ──
|
||||
|
||||
_ID_RE = re.compile(r"([0-9a-fA-F]{32})")
|
||||
@@ -622,6 +649,7 @@ class AutoStudyWorker:
|
||||
self._thread: threading.Thread | None = None
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._async_stop: asyncio.Event | None = None
|
||||
self._kick: asyncio.Event | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True)
|
||||
@@ -632,10 +660,15 @@ class AutoStudyWorker:
|
||||
if self._loop and self._async_stop:
|
||||
self._loop.call_soon_threadsafe(self._async_stop.set)
|
||||
|
||||
def wake(self) -> None:
|
||||
if self._loop and self._kick is not None:
|
||||
self._loop.call_soon_threadsafe(self._kick.set)
|
||||
|
||||
def _run_thread(self) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._async_stop = asyncio.Event()
|
||||
self._kick = asyncio.Event()
|
||||
try:
|
||||
self._loop.run_until_complete(self._main_loop())
|
||||
finally:
|
||||
@@ -643,18 +676,20 @@ class AutoStudyWorker:
|
||||
|
||||
async def _main_loop(self) -> None:
|
||||
assert self._async_stop is not None
|
||||
await asyncio.sleep(15)
|
||||
assert self._kick is not None
|
||||
await wait_stop(15, self._async_stop, self._kick)
|
||||
while not self._async_stop.is_set():
|
||||
self._kick.clear()
|
||||
try:
|
||||
await self._run_cycle()
|
||||
except Exception as exc:
|
||||
log.exception("自动学习周期异常: %s", exc)
|
||||
_set_status(message=f"异常: {exc}")
|
||||
try:
|
||||
await asyncio.wait_for(self._async_stop.wait(), timeout=random.uniform(300, 600))
|
||||
if self._async_stop.is_set():
|
||||
return
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if self._kick.is_set():
|
||||
continue
|
||||
await wait_stop(random.uniform(300, 600), self._async_stop, self._kick)
|
||||
|
||||
async def _run_cycle(self) -> None:
|
||||
assert self._async_stop is not None
|
||||
@@ -681,8 +716,12 @@ class AutoStudyWorker:
|
||||
course_list = [(c.path, c.title, c.kind) for c in courses]
|
||||
eligible = []
|
||||
waiting = 0
|
||||
paused = 0
|
||||
for row in users:
|
||||
if not window_open(row):
|
||||
if not study_eligible(row):
|
||||
if getattr(row, "study_paused", False):
|
||||
paused += 1
|
||||
else:
|
||||
waiting += 1
|
||||
continue
|
||||
target = row.monthly_target or 600
|
||||
@@ -713,6 +752,8 @@ class AutoStudyWorker:
|
||||
if not eligible:
|
||||
if waiting:
|
||||
_set_status(running=False, message="未到开始时间或已达标")
|
||||
elif paused:
|
||||
_set_status(running=False, message="任务已停止")
|
||||
else:
|
||||
_set_status(running=False, message="所有用户已达标或无有效凭据")
|
||||
return
|
||||
@@ -740,8 +781,17 @@ class AutoStudyWorker:
|
||||
workers: int, use_pool: bool, course_list: list, intervals: dict,
|
||||
auto_mode: bool, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
user_stop = asyncio.Event()
|
||||
with _halt_lock:
|
||||
current = _user_halts.get(employee_id)
|
||||
if current is not None and not current.is_set():
|
||||
return
|
||||
_user_halts[employee_id] = user_stop
|
||||
try:
|
||||
async with sem:
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
_set_user_status(employee_id, state="准备", course="")
|
||||
loop = asyncio.get_event_loop()
|
||||
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
|
||||
@@ -755,7 +805,6 @@ class AutoStudyWorker:
|
||||
) as session:
|
||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
||||
_set_user_status(employee_id, state="学习中")
|
||||
user_stop = asyncio.Event()
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop)
|
||||
if await hours.refresh():
|
||||
return
|
||||
@@ -769,6 +818,9 @@ class AutoStudyWorker:
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await ticker
|
||||
finally:
|
||||
with _halt_lock:
|
||||
if _user_halts.get(employee_id) is user_stop:
|
||||
_user_halts.pop(employee_id, None)
|
||||
if use_pool:
|
||||
from euniv.proxy_pool import release
|
||||
|
||||
@@ -861,9 +913,6 @@ def _update_month_hours(employee_id: str, hours: str) -> None:
|
||||
|
||||
# ── 启动入口 ──
|
||||
|
||||
_worker: AutoStudyWorker | None = None
|
||||
|
||||
|
||||
def start_autostudy() -> AutoStudyWorker:
|
||||
global _worker
|
||||
w = AutoStudyWorker()
|
||||
|
||||
@@ -116,6 +116,45 @@ def _by_closeness(items: list[dict], key: str) -> list[dict]:
|
||||
return ordered
|
||||
|
||||
|
||||
_HISTORY_ROW_RE = re.compile(
|
||||
r'<tr class="alter">\s*'
|
||||
r'<td class="text-left" title="([^"]*)">([\s\S]*?)</td>\s*'
|
||||
r'<td class="text-center">\s*(\d+)\s*</td>\s*'
|
||||
r'<td class="text-center">\s*([^<]+?)\s*</td>',
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def _history_api_item(row: object) -> dict | None:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
title = str(row.get("targetName") or row.get("title") or row.get("kngName") or "").strip()
|
||||
studied_at = str(row.get("studyDate") or row.get("studiedAt") or row.get("createTime") or "").strip()
|
||||
raw_minutes = row.get("duration")
|
||||
if raw_minutes is None:
|
||||
raw_minutes = row.get("studyHour")
|
||||
minutes: int | None = None
|
||||
if isinstance(raw_minutes, bool):
|
||||
minutes = None
|
||||
elif isinstance(raw_minutes, (int, float)):
|
||||
minutes = int(raw_minutes)
|
||||
elif isinstance(raw_minutes, str) and raw_minutes.strip():
|
||||
match = re.search(r"(\d+)", raw_minutes)
|
||||
minutes = int(match.group(1)) if match else None
|
||||
path = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip()
|
||||
knowledge_id = str(row.get("knowledgeId") or row.get("kngId") or "").replace("-", "")
|
||||
if not path and len(knowledge_id) == 32:
|
||||
path = f"/kng/view/document/{knowledge_id}.html"
|
||||
if not title and not studied_at:
|
||||
return None
|
||||
return {
|
||||
"title": title,
|
||||
"minutes": minutes,
|
||||
"studied_at": studied_at,
|
||||
"path": path,
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
@@ -756,6 +795,57 @@ class EunivClient:
|
||||
def month_hours(self) -> str:
|
||||
return self._period_minutes().get("month", "")
|
||||
|
||||
def study_history(self) -> list[dict]:
|
||||
"""读取「我的学时」列表:来源、获得学时(分钟)、日期。"""
|
||||
try:
|
||||
items = self._study_history_api()
|
||||
except Exception:
|
||||
items = None
|
||||
if items is not None:
|
||||
return items
|
||||
return self._study_history_page()
|
||||
|
||||
def _study_history_api(self) -> list[dict] | None:
|
||||
response = self._request(
|
||||
"POST",
|
||||
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
|
||||
json={"pageable": False},
|
||||
)
|
||||
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
|
||||
|
||||
def _study_history_page(self) -> list[dict]:
|
||||
text = self._study_period_page()
|
||||
items = []
|
||||
for match in _HISTORY_ROW_RE.finditer(text):
|
||||
title = unescape(match.group(1) or "").strip()
|
||||
cell = match.group(2) or ""
|
||||
minutes = int(match.group(3))
|
||||
studied_at = unescape(match.group(4) or "").strip()
|
||||
path_match = re.search(r"GoToSource\('([^']+)'", cell)
|
||||
path = path_match.group(1) if path_match else ""
|
||||
items.append(
|
||||
{
|
||||
"title": title,
|
||||
"minutes": minutes,
|
||||
"studied_at": studied_at,
|
||||
"path": path,
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
def _period_minutes(self) -> dict[str, str]:
|
||||
text = self._study_period_page()
|
||||
found = {}
|
||||
|
||||
@@ -58,6 +58,8 @@ class Account(Base):
|
||||
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
|
||||
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
|
||||
use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
study_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
study_ignore_window: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
|
||||
|
||||
class ProxyNode(Base):
|
||||
|
||||
@@ -13,7 +13,7 @@ import httpx
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EUNIV, USER_AGENT
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
|
||||
from euniv.collectors import collect_all, is_china, source_title
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import ProxyNode, ProxyPoolSync
|
||||
@@ -21,6 +21,10 @@ from euniv.proxy import build_proxy_url
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProxyProbeError(ValueError):
|
||||
"""延迟测试目标不存在。"""
|
||||
|
||||
FETCH_INTERVAL = 300
|
||||
LATENCY_LIMIT = 3.0
|
||||
LATENCY_LIMIT_MS = 3000
|
||||
@@ -28,6 +32,11 @@ PROBE_CONCURRENCY = 16
|
||||
MAX_PROBES = 80
|
||||
MAX_SWITCHES = 8
|
||||
PROBE_URL = EUNIV + "/"
|
||||
PROBE_URLS = (
|
||||
EUNIV + "/",
|
||||
STUDY_API + "/",
|
||||
YXT_API + "/",
|
||||
)
|
||||
STATUS_ALIVE = "alive"
|
||||
STATUS_DEAD = "dead"
|
||||
STATUS_NEW = "new"
|
||||
@@ -154,7 +163,8 @@ def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int
|
||||
|
||||
def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
url = build_proxy_url(scheme, host, port)
|
||||
started = time.perf_counter()
|
||||
samples: list[int] = []
|
||||
reasons: list[str] = []
|
||||
try:
|
||||
with httpx.Client(
|
||||
proxy=url,
|
||||
@@ -162,16 +172,29 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
) as client:
|
||||
response = client.get(PROBE_URL)
|
||||
for target in PROBE_URLS:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = client.get(target)
|
||||
latency = int((time.perf_counter() - started) * 1000)
|
||||
if latency > LATENCY_LIMIT_MS:
|
||||
return False, latency, "超时"
|
||||
if response.status_code >= 500:
|
||||
return False, latency, f"HTTP {response.status_code}"
|
||||
return True, latency, ""
|
||||
samples.append(max(latency, LATENCY_LIMIT_MS))
|
||||
reasons.append(f"HTTP {response.status_code}")
|
||||
continue
|
||||
samples.append(latency)
|
||||
except Exception as exc:
|
||||
latency = int((time.perf_counter() - started) * 1000)
|
||||
return False, latency, _short_reason(exc)
|
||||
samples.append(int((time.perf_counter() - started) * 1000) or LATENCY_LIMIT_MS)
|
||||
reasons.append(_short_reason(exc))
|
||||
except Exception as exc:
|
||||
return False, LATENCY_LIMIT_MS, _short_reason(exc)
|
||||
if not samples:
|
||||
return False, LATENCY_LIMIT_MS, reasons[0] if reasons else "无法连接"
|
||||
average = int(round(sum(samples) / len(samples)))
|
||||
if reasons:
|
||||
return False, average, reasons[0]
|
||||
if average > LATENCY_LIMIT_MS:
|
||||
return False, average, "超时"
|
||||
return True, average, ""
|
||||
|
||||
|
||||
def _short_reason(exc: BaseException) -> str:
|
||||
@@ -413,6 +436,69 @@ def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool,
|
||||
return results
|
||||
|
||||
|
||||
def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
|
||||
node.last_checked_at = _now()
|
||||
node.latency_ms = latency
|
||||
if ok:
|
||||
node.status = STATUS_ALIVE
|
||||
node.last_ok_at = node.last_checked_at
|
||||
node.fail_reason = ""
|
||||
else:
|
||||
node.status = STATUS_DEAD
|
||||
node.fail_reason = (reason or "失效")[:200]
|
||||
_evict_node(node.id)
|
||||
|
||||
|
||||
def probe_one(node_id: int) -> dict:
|
||||
with SessionLocal() as db:
|
||||
node = db.get(ProxyNode, node_id)
|
||||
if node is None:
|
||||
raise ProxyProbeError("代理不存在")
|
||||
snapshot = (node.id, node.scheme, node.host, int(node.port))
|
||||
ok, latency, reason = probe(snapshot[1], snapshot[2], snapshot[3])
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
node = db.get(ProxyNode, node_id)
|
||||
if node is None:
|
||||
raise ProxyProbeError("代理不存在")
|
||||
_apply_probe(node, ok, latency, reason)
|
||||
db.commit()
|
||||
return view_item(node)
|
||||
|
||||
|
||||
def probe_ids(ids: list[int] | None = None) -> dict:
|
||||
with SessionLocal() as db:
|
||||
if ids:
|
||||
wanted = []
|
||||
seen: set[int] = set()
|
||||
for raw in ids:
|
||||
node_id = int(raw)
|
||||
if node_id in seen:
|
||||
continue
|
||||
seen.add(node_id)
|
||||
wanted.append(node_id)
|
||||
nodes = [
|
||||
node
|
||||
for node in (db.get(ProxyNode, node_id) for node_id in wanted)
|
||||
if node is not None
|
||||
]
|
||||
if len(nodes) != len(wanted):
|
||||
raise ProxyProbeError("代理不存在")
|
||||
else:
|
||||
nodes = list(db.scalars(select(ProxyNode).order_by(ProxyNode.id)).all())
|
||||
snapshot = [(node.id, node.scheme, node.host, int(node.port)) for node in nodes]
|
||||
results = _probe_many(snapshot)
|
||||
items = []
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
for node_id, ok, latency, reason in results:
|
||||
node = db.get(ProxyNode, node_id)
|
||||
if node is None:
|
||||
continue
|
||||
_apply_probe(node, ok, latency, reason)
|
||||
items.append(view_item(node))
|
||||
db.commit()
|
||||
return {"ok": True, "count": len(items), "items": items}
|
||||
|
||||
|
||||
def request_refresh() -> dict:
|
||||
with SessionLocal() as db:
|
||||
sync = _sync_row(db)
|
||||
|
||||
@@ -205,6 +205,13 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto
|
||||
return _live(db, employee_id, client_factory, lambda client: client.training_detail(path))
|
||||
|
||||
|
||||
def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
items = _live(db, employee_id, client_factory, lambda client: client.study_history())
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
def _auto_attempts(db: Session) -> int:
|
||||
from admin.settings import auto_attempt_count
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""账号自动学习任务的立即开始与停止。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from euniv.study_window import window_open
|
||||
|
||||
|
||||
class StudyControlError(ValueError):
|
||||
"""任务控制参数不符合要求。"""
|
||||
|
||||
|
||||
def start_now(account) -> None:
|
||||
account.study_paused = False
|
||||
account.study_ignore_window = True
|
||||
|
||||
|
||||
def stop_now(account) -> None:
|
||||
account.study_paused = True
|
||||
account.study_ignore_window = False
|
||||
|
||||
|
||||
def is_paused(account) -> bool:
|
||||
return bool(getattr(account, "study_paused", False))
|
||||
|
||||
|
||||
def ignores_window(account) -> bool:
|
||||
return bool(getattr(account, "study_ignore_window", False))
|
||||
|
||||
|
||||
def eligible(account) -> bool:
|
||||
if is_paused(account):
|
||||
return False
|
||||
if ignores_window(account):
|
||||
return True
|
||||
return window_open(account)
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
paused = is_paused(account)
|
||||
ignore = ignores_window(account)
|
||||
opened = window_open(account)
|
||||
started = (not paused) and (ignore or opened)
|
||||
return {
|
||||
"paused": paused,
|
||||
"ignore_window": ignore,
|
||||
"window_open": opened,
|
||||
"started": started,
|
||||
}
|
||||
@@ -445,6 +445,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"last_refresh_at",
|
||||
"credential_valid",
|
||||
"month_hours",
|
||||
"monthly_target",
|
||||
"has_proxy",
|
||||
"proxy",
|
||||
"study_start",
|
||||
@@ -453,6 +454,9 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
"study_paused",
|
||||
"study_ignore_window",
|
||||
"study_started",
|
||||
}
|
||||
assert saved["has_credential"] is True
|
||||
assert saved["refresh_paused"] is False
|
||||
@@ -791,3 +795,60 @@ def test_admin_can_turn_off_proxy_with_scheme() -> None:
|
||||
detail = client.get("/api/admin/users/off-user/proxy")
|
||||
assert detail.json()["enabled"] is False
|
||||
assert detail.json()["scheme"] == "off"
|
||||
|
||||
|
||||
def test_admin_can_start_and_stop_study_for_selected_users() -> None:
|
||||
_add_account("run-user")
|
||||
_add_account("wait-user")
|
||||
api = _app()
|
||||
client = TestClient(api.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
started = client.post("/api/admin/users/study", json={"employee_ids": ["run-user", "wait-user"], "action": "start"})
|
||||
assert started.status_code == 200
|
||||
assert started.json()["count"] == 2
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "run-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "wait-user")
|
||||
assert one["study_started"] is True
|
||||
assert two["study_paused"] is False
|
||||
stopped = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "stop"})
|
||||
assert stopped.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "run-user")
|
||||
two = next(item for item in listed if item["employee_id"] == "wait-user")
|
||||
assert one["study_started"] is False
|
||||
assert one["study_paused"] is True
|
||||
assert two["study_started"] is True
|
||||
bad = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "pause"})
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_admin_can_save_study_settings_in_one_request() -> None:
|
||||
_add_account("set-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-settings",
|
||||
json={
|
||||
"employee_ids": ["set-user"],
|
||||
"monthly_target": 120,
|
||||
"day": 8,
|
||||
"hour": 9,
|
||||
"minute": 10,
|
||||
"second": 11,
|
||||
"workers": 2,
|
||||
"scheme": "http",
|
||||
"host": "10.0.0.8",
|
||||
"port": 8080,
|
||||
"username": "",
|
||||
"password": "",
|
||||
},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
listed = client.get("/api/admin/users").json()
|
||||
one = next(item for item in listed if item["employee_id"] == "set-user")
|
||||
assert one["monthly_target"] == 120
|
||||
assert one["study_start"] == "每月8日 09:10:11"
|
||||
assert one["course_workers"] == 2
|
||||
assert one["proxy"] == "HTTP 10.0.0.8:8080"
|
||||
|
||||
@@ -65,6 +65,16 @@ class FakeClient:
|
||||
"unionId": credential["ucs_union_id"],
|
||||
}
|
||||
|
||||
def study_history(self) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)",
|
||||
"minutes": 2,
|
||||
"studied_at": "2026-11-14 23:55",
|
||||
"path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html",
|
||||
}
|
||||
]
|
||||
|
||||
def home_snapshot(self) -> dict:
|
||||
if self._token == "yxt-1":
|
||||
self._token = "yxt-2"
|
||||
@@ -123,6 +133,8 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"study_start_second",
|
||||
"course_workers",
|
||||
"use_proxy_pool",
|
||||
"study_paused",
|
||||
"study_ignore_window",
|
||||
}
|
||||
|
||||
home = client.get("/api/home")
|
||||
@@ -538,6 +550,82 @@ def test_user_can_set_monthly_study_start() -> None:
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_user_can_start_and_stop_study_immediately() -> 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
|
||||
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
|
||||
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
|
||||
stopped = client.post("/api/settings/study-control", json={"action": "stop"})
|
||||
assert stopped.status_code == 200
|
||||
assert stopped.json()["started"] is False
|
||||
assert stopped.json()["paused"] is True
|
||||
assert stopped.json()["ignore_window"] is False
|
||||
bad = client.post("/api/settings/study-control", json={"action": "pause"})
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_user_can_read_study_history() -> 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
|
||||
)
|
||||
api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history(
|
||||
db, employee_id, FakeClient
|
||||
)
|
||||
client = TestClient(api_module.app)
|
||||
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
||||
history = client.get("/api/home/history")
|
||||
assert history.status_code == 200
|
||||
body = history.json()
|
||||
assert body["total"] == 1
|
||||
assert body["items"][0]["title"].startswith("ZXCTN")
|
||||
assert body["items"][0]["minutes"] == 2
|
||||
|
||||
|
||||
def test_study_history_parses_period_table() -> None:
|
||||
from euniv.client import EunivClient
|
||||
|
||||
html = """
|
||||
<table class="table mt5 mb10">
|
||||
<tr><th>来源</th><th>学时</th><th>日期</th></tr>
|
||||
<tr class="alter">
|
||||
<td class="text-left" title="ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)">
|
||||
ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)
|
||||
<span onclick="GoToSource('/kng/view/document/125c7576c22e4ae7be92ce005171facb.html','SingleStudy','125c7576-c22e-4ae7-be92-ce005171facb')"
|
||||
class='text-info hand '>[详情]</span>
|
||||
</td>
|
||||
<td class="text-center">2</td>
|
||||
<td class="text-center">2026-11-14 23:55</td>
|
||||
</tr>
|
||||
</table>
|
||||
"""
|
||||
client = EunivClient.__new__(EunivClient)
|
||||
client._study_period_page = lambda: html # type: ignore[method-assign]
|
||||
rows = client._study_history_page()
|
||||
assert rows == [
|
||||
{
|
||||
"title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)",
|
||||
"minutes": 2,
|
||||
"studied_at": "2026-11-14 23:55",
|
||||
"path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_exam_list_rejects_unrecognized_page() -> None:
|
||||
from euniv.client import EunivClient
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from datetime import datetime
|
||||
from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
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
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
|
||||
|
||||
|
||||
@@ -172,6 +173,8 @@ class _Start:
|
||||
self.study_start_hour = hour
|
||||
self.study_start_minute = minute
|
||||
self.study_start_second = second
|
||||
self.study_paused = False
|
||||
self.study_ignore_window = False
|
||||
|
||||
|
||||
def test_study_window_opens_after_configured_time() -> None:
|
||||
@@ -188,6 +191,19 @@ def test_study_window_clamps_missing_day() -> None:
|
||||
assert window_open(account, datetime(2026, 2, 28, 16, 0, 0, tzinfo=CN_TZ)) is True
|
||||
|
||||
|
||||
def test_immediate_start_skips_monthly_window() -> None:
|
||||
account = _Start(28, 23, 59, 59)
|
||||
assert study_eligible(account) is False
|
||||
start_now(account)
|
||||
assert account.study_paused is False
|
||||
assert account.study_ignore_window is True
|
||||
assert study_eligible(account) is True
|
||||
stop_now(account)
|
||||
assert account.study_paused is True
|
||||
assert account.study_ignore_window is False
|
||||
assert study_eligible(account) is False
|
||||
|
||||
|
||||
def test_study_window_rejects_invalid_parts() -> None:
|
||||
with pytest.raises(StudyWindowError):
|
||||
validate_start(32, 0, 0, 0)
|
||||
|
||||
@@ -7,7 +7,7 @@ from euniv.db import SessionLocal
|
||||
from euniv.models import Account, ProxyNode
|
||||
from euniv.proxy import apply as apply_proxy
|
||||
from euniv.proxy import bind_url, is_proxy_failure, view_of
|
||||
from euniv.proxy_pool import acquire, mark_failed, page, refresh_once, release
|
||||
from euniv.proxy_pool import PROBE_URLS, acquire, mark_failed, page, probe, refresh_once, release
|
||||
from euniv.proxy_pool import _holds
|
||||
|
||||
INITIAL_PASSWORD = "242520"
|
||||
@@ -189,6 +189,57 @@ def test_failed_proxy_is_not_reprobed(monkeypatch) -> None:
|
||||
assert node.status == "dead"
|
||||
|
||||
|
||||
def test_probe_averages_euniv_related_sites(monkeypatch) -> None:
|
||||
seen: list[str] = []
|
||||
|
||||
class FakeResponse:
|
||||
status_code = 200
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args) -> bool:
|
||||
return False
|
||||
|
||||
def get(self, url: str):
|
||||
seen.append(url)
|
||||
return FakeResponse()
|
||||
|
||||
ticks = iter([0.0, 0.12, 0.12, 0.34, 0.34, 0.64])
|
||||
monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient)
|
||||
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
|
||||
ok, latency, reason = probe("http", "10.0.0.9", 8080)
|
||||
assert seen == list(PROBE_URLS)
|
||||
assert ok is True
|
||||
assert latency == 213
|
||||
assert reason == ""
|
||||
|
||||
|
||||
def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None:
|
||||
import euniv.api as api_module
|
||||
|
||||
_holds.clear()
|
||||
one = _node("10.0.0.7", 8007)
|
||||
two = _node("10.0.0.8", 8008, status="new")
|
||||
monkeypatch.setattr("euniv.proxy_pool.probe", lambda scheme, host, port: (True, 321 if host.endswith("7") else 654, ""))
|
||||
client = TestClient(api_module.app)
|
||||
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
||||
single = client.post(f"/api/admin/proxies/{one.id}/probe")
|
||||
assert single.status_code == 200
|
||||
assert single.json()["latency_ms"] == 321
|
||||
assert single.json()["status"] == "alive"
|
||||
bulk = client.post("/api/admin/proxies/probe", json={"ids": [two.id]})
|
||||
assert bulk.status_code == 200
|
||||
assert bulk.json()["count"] == 1
|
||||
assert bulk.json()["items"][0]["latency_ms"] == 654
|
||||
missing = client.post("/api/admin/proxies/99999/probe")
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_is_proxy_failure_detects_connect_errors() -> None:
|
||||
assert is_proxy_failure(httpx.ConnectError("boom"))
|
||||
assert is_proxy_failure(httpx.ConnectTimeout("late"))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { NAlert, NButton, NInput, NPagination } from "naive-ui";
|
||||
import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui";
|
||||
import { DownloadOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface CourseRow {
|
||||
title: string;
|
||||
@@ -173,7 +174,14 @@ onUnmounted(() => stopPoll());
|
||||
</p>
|
||||
</div>
|
||||
<form class="course-search" @submit.prevent="search">
|
||||
<n-button attr-type="button" :loading="fetching" :disabled="fetching" @click="loadCourses">加载课程列表</n-button>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle attr-type="button" :loading="fetching" :disabled="fetching" aria-label="加载课程列表" @click="loadCourses">
|
||||
<template #icon><n-icon><DownloadOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
加载课程列表
|
||||
</n-tooltip>
|
||||
<n-input v-model:value="query" placeholder="名称或贡献者" clearable @clear="search" />
|
||||
<n-button attr-type="submit">搜索</n-button>
|
||||
</form>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { NAlert, NButton, NInput, NPagination } from "naive-ui";
|
||||
import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui";
|
||||
import { FlashOutline, RefreshOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface ProxyRow {
|
||||
id: number;
|
||||
@@ -38,6 +39,8 @@ const page = ref(1);
|
||||
const pageSize = ref(50);
|
||||
const pageSizes = [20, 50, 100];
|
||||
const fetching = ref(false);
|
||||
const probingId = ref<number | null>(null);
|
||||
const probingAll = ref(false);
|
||||
let poll = 0;
|
||||
|
||||
const kinds = computed<StatusOption[]>(() => [
|
||||
@@ -143,6 +146,53 @@ function stopPoll() {
|
||||
poll = 0;
|
||||
}
|
||||
|
||||
function applyProbed(row: ProxyRow) {
|
||||
items.value = items.value.map((item) => (item.id === row.id ? row : item));
|
||||
}
|
||||
|
||||
async function probeOne(row: ProxyRow) {
|
||||
if (probingId.value != null || probingAll.value || fetching.value) return;
|
||||
probingId.value = row.id;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = isRecord(payload) && typeof payload.detail === "string" ? payload.detail : "没有测出延迟。";
|
||||
return;
|
||||
}
|
||||
const next = asRow(payload);
|
||||
if (next) applyProbed(next);
|
||||
} catch {
|
||||
errorText.value = "没有测出延迟。";
|
||||
} finally {
|
||||
probingId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probeAll() {
|
||||
if (probingId.value != null || probingAll.value || fetching.value || !items.value.length) return;
|
||||
probingAll.value = true;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch("/api/admin/proxies/probe", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = isRecord(payload) && typeof payload.detail === "string" ? payload.detail : "没有测出延迟。";
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
} catch {
|
||||
errorText.value = "没有测出延迟。";
|
||||
} finally {
|
||||
probingAll.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshNow() {
|
||||
errorText.value = "";
|
||||
fetching.value = true;
|
||||
@@ -203,7 +253,22 @@ onUnmounted(() => stopPoll());
|
||||
</p>
|
||||
</div>
|
||||
<form class="course-search" @submit.prevent="search">
|
||||
<n-button attr-type="button" :loading="fetching" :disabled="fetching" @click="refreshNow">立即更新</n-button>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle attr-type="button" :loading="fetching" :disabled="fetching || probingAll" aria-label="立即更新" @click="refreshNow">
|
||||
<template #icon><n-icon><RefreshOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</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-input v-model:value="query" placeholder="地址" clearable @clear="search" />
|
||||
<n-button attr-type="submit">搜索</n-button>
|
||||
</form>
|
||||
@@ -238,6 +303,7 @@ onUnmounted(() => stopPoll());
|
||||
<th>延迟</th>
|
||||
<th>状态</th>
|
||||
<th>检测时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -251,6 +317,24 @@ onUnmounted(() => stopPoll());
|
||||
<td class="when">{{ formatLatency(row.latency_ms) }}</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>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NInput, NInputNumber, NRadioButton, NRadioGroup, NSwitch } from "naive-ui";
|
||||
import { NAlert, NButton, NForm, NFormItem, NInput, NInputNumber, NRadioButton, NRadioGroup, NSwitch } from "naive-ui";
|
||||
|
||||
const emit = defineEmits<{ saved: [] }>();
|
||||
|
||||
@@ -160,77 +160,79 @@ async function save() {
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<n-alert v-else-if="successText" class="admin-alert" type="success">{{ successText }}</n-alert>
|
||||
<div class="admin-scroll">
|
||||
<div class="admin-scroll settings-stack">
|
||||
<p v-if="loading && !loaded" class="admin-status">正在获取</p>
|
||||
<div v-else-if="loaded">
|
||||
<div class="form-row">
|
||||
<label for="refresh-interval">定时刷新间隔</label>
|
||||
<div class="setting-control">
|
||||
<template v-else-if="loaded">
|
||||
<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="定时刷新间隔">
|
||||
<div class="target-control">
|
||||
<n-input-number id="refresh-interval" v-model:value="refreshInterval" button-placement="both" :min="1" :max="1440" :precision="0" />
|
||||
<span class="setting-unit">分钟</span>
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="show-manual">显示手动滑动验证码</label>
|
||||
<n-switch id="show-manual" v-model:value="showManualJigsaw" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="manual-preference">{{ preferenceLabel }}</label>
|
||||
<n-switch id="manual-preference" v-model:value="manualPreference" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="auto-attempts">自动滑动次数</label>
|
||||
<div class="setting-control">
|
||||
</n-form-item>
|
||||
<n-form-item label="显示手动滑动验证码">
|
||||
<n-switch v-model:value="showManualJigsaw" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="preferenceLabel">
|
||||
<n-switch v-model:value="manualPreference" />
|
||||
</n-form-item>
|
||||
<n-form-item label="自动滑动次数">
|
||||
<div class="target-control">
|
||||
<n-input-number id="auto-attempts" v-model:value="attempts" button-placement="both" :min="1" :max="10" :precision="0" />
|
||||
<span class="setting-unit">次</span>
|
||||
<span class="target-unit">次</span>
|
||||
</div>
|
||||
</div>
|
||||
<h3 class="form-section">自动学习心跳间隔</h3>
|
||||
<div class="form-row">
|
||||
<label>间隔来源</label>
|
||||
</n-form-item>
|
||||
</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="hbMode" size="small">
|
||||
<n-radio-button value="auto">自动获取</n-radio-button>
|
||||
<n-radio-button value="manual">手动设定</n-radio-button>
|
||||
</n-radio-group>
|
||||
</div>
|
||||
<template v-if="hbMode === 'manual'">
|
||||
<div class="form-row">
|
||||
<label for="hb-video">视频</label>
|
||||
<div class="setting-control">
|
||||
</n-form-item>
|
||||
<p v-if="hbMode === 'auto'" class="form-hint">每次自动学习时从课程播放页读取间隔</p>
|
||||
<template v-else>
|
||||
<n-form-item label="视频">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="10" :max="300" :precision="0" />
|
||||
<span class="setting-unit">秒</span>
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="hb-document">文档</label>
|
||||
<div class="setting-control">
|
||||
</n-form-item>
|
||||
<n-form-item label="文档">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||
<span class="setting-unit">秒</span>
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="hb-scorm">Scorm</label>
|
||||
<div class="setting-control">
|
||||
</n-form-item>
|
||||
<n-form-item label="Scorm">
|
||||
<div class="target-control">
|
||||
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||
<span class="setting-unit">秒</span>
|
||||
</div>
|
||||
<span class="target-unit">秒</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</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-input v-model:value="username" autocomplete="username" />
|
||||
</n-form-item>
|
||||
<n-form-item label="新密码">
|
||||
<n-input v-model:value="password" type="password" show-password-on="click" placeholder="请输入" autocomplete="new-password" />
|
||||
</n-form-item>
|
||||
<n-form-item label="再输入一次">
|
||||
<n-input v-model:value="confirmPassword" type="password" show-password-on="click" placeholder="请输入" autocomplete="new-password" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</section>
|
||||
</template>
|
||||
<p v-else class="form-hint">自动获取:每次自动学习时从课程播放页在线读取间隔</p>
|
||||
<h3 class="form-section">管理员</h3>
|
||||
<div class="form-row">
|
||||
<label for="admin-username">管理员用户名</label>
|
||||
<n-input id="admin-username" v-model:value="username" autocomplete="username" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-password">新密码</label>
|
||||
<n-input id="admin-password" v-model:value="password" type="password" show-password-on="click" autocomplete="new-password" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-password-again">再输入一次</label>
|
||||
<n-input id="admin-password-again" v-model:value="confirmPassword" type="password" show-password-on="click" autocomplete="new-password" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NCheckbox, NDropdown, NIcon, NInput, NInputNumber, NModal, NSelect, NTooltip, useDialog, type DropdownOption } from "naive-ui";
|
||||
import { HelpCircleOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
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";
|
||||
|
||||
interface UserRow {
|
||||
employee_id: string;
|
||||
@@ -10,6 +10,7 @@ interface UserRow {
|
||||
last_refresh_at: string | null;
|
||||
credential_valid: boolean | null;
|
||||
month_hours: string;
|
||||
monthly_target: number;
|
||||
has_proxy: boolean;
|
||||
proxy: string;
|
||||
study_start: string;
|
||||
@@ -18,6 +19,9 @@ interface UserRow {
|
||||
study_start_minute: number;
|
||||
study_start_second: number;
|
||||
course_workers: number;
|
||||
study_paused: boolean;
|
||||
study_ignore_window: boolean;
|
||||
study_started: boolean;
|
||||
}
|
||||
|
||||
interface SecretField {
|
||||
@@ -32,6 +36,7 @@ const users = ref<UserRow[]>([]);
|
||||
const liveResults = ref<Record<string, string>>({});
|
||||
const checkingId = ref("");
|
||||
const checkingAll = ref(false);
|
||||
const studyBusy = ref(false);
|
||||
const credentialOpen = ref(false);
|
||||
const credentialTitle = ref("凭据");
|
||||
const credentialLoading = ref(false);
|
||||
@@ -39,10 +44,16 @@ const credentialError = ref("");
|
||||
const credentialNote = ref("");
|
||||
const credentialFields = ref<SecretField[]>([]);
|
||||
const picked = ref<Record<string, boolean>>({});
|
||||
const proxyOpen = ref(false);
|
||||
const proxySaving = ref(false);
|
||||
const proxyError = ref("");
|
||||
const proxyIds = ref<string[]>([]);
|
||||
const settingsOpen = ref(false);
|
||||
const settingsSaving = ref(false);
|
||||
const settingsError = ref("");
|
||||
const settingsIds = ref<string[]>([]);
|
||||
const monthlyTarget = ref<number | null>(600);
|
||||
const startDay = ref<number | null>(1);
|
||||
const startHour = ref<number | null>(0);
|
||||
const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
const workersValue = ref<number | null>(1);
|
||||
const proxyScheme = ref("off");
|
||||
const proxyHost = ref("");
|
||||
const proxyPort = ref<number | null>(null);
|
||||
@@ -58,23 +69,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<string[]>([]);
|
||||
const startDay = ref<number | null>(1);
|
||||
const startHour = ref<number | null>(0);
|
||||
const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
const workersOpen = ref(false);
|
||||
const workersSaving = ref(false);
|
||||
const workersError = ref("");
|
||||
const workersIds = ref<string[]>([]);
|
||||
const workersValue = ref<number | null>(1);
|
||||
|
||||
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);
|
||||
const somePicked = computed(() => pickedIds.value.length > 0 && !allPicked.value);
|
||||
const moreOptions = computed<DropdownOption[]>(() => [
|
||||
{ label: "检查全部", key: "check-all", disabled: checkingAll.value || checkingId.value !== "" || !users.value.length },
|
||||
{ label: "清除代理", key: "clear-proxy", disabled: !pickedIds.value.length },
|
||||
]);
|
||||
|
||||
const tokenFields: { label: string; key: string }[] = [
|
||||
{ label: "统一认证 token", key: "ucs_token" },
|
||||
@@ -85,6 +87,24 @@ const tokenFields: { label: string; key: string }[] = [
|
||||
{ label: "学习平台 token", key: "yxt_token" },
|
||||
];
|
||||
|
||||
function pad(value: number) {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
const startTime = computed({
|
||||
get() {
|
||||
return `${pad(startHour.value ?? 0)}:${pad(startMinute.value ?? 0)}:${pad(startSecond.value ?? 0)}`;
|
||||
},
|
||||
set(value: string | null) {
|
||||
if (!value) return;
|
||||
const [hour, minute, second] = value.split(":").map((part) => Number(part));
|
||||
if (![hour, minute, second].every((part) => Number.isInteger(part))) return;
|
||||
startHour.value = hour;
|
||||
startMinute.value = minute;
|
||||
startSecond.value = second;
|
||||
},
|
||||
});
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -113,6 +133,7 @@ function asUser(value: unknown): UserRow | null {
|
||||
last_refresh_at: typeof value.last_refresh_at === "string" && value.last_refresh_at ? value.last_refresh_at : null,
|
||||
credential_valid: readValid(value.credential_valid),
|
||||
month_hours: textOf(value.month_hours),
|
||||
monthly_target: typeof value.monthly_target === "number" ? value.monthly_target : 600,
|
||||
has_proxy: value.has_proxy === true,
|
||||
proxy: textOf(value.proxy),
|
||||
study_start: textOf(value.study_start),
|
||||
@@ -121,6 +142,9 @@ function asUser(value: unknown): UserRow | null {
|
||||
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,
|
||||
course_workers: typeof value.course_workers === "number" ? value.course_workers : 1,
|
||||
study_paused: value.study_paused === true,
|
||||
study_ignore_window: value.study_ignore_window === true,
|
||||
study_started: value.study_started === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -128,8 +152,8 @@ function formatRefreshTime(value: string | null) {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (part: number) => String(part).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
const padPart = (part: number) => String(part).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${padPart(date.getMonth() + 1)}-${padPart(date.getDate())} ${padPart(date.getHours())}:${padPart(date.getMinutes())}:${padPart(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
function checkLabel(payload: Record<string, unknown>) {
|
||||
@@ -154,6 +178,12 @@ function validityClass(text: string) {
|
||||
return "quiet";
|
||||
}
|
||||
|
||||
function taskText(row: UserRow) {
|
||||
if (row.study_started) return "已开始";
|
||||
if (row.study_paused) return "已停止";
|
||||
return "未开始";
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
@@ -351,22 +381,39 @@ function toggleAll(checked: boolean) {
|
||||
picked.value = next;
|
||||
}
|
||||
|
||||
function resetProxyForm() {
|
||||
function resetSettingsForm() {
|
||||
monthlyTarget.value = 600;
|
||||
startDay.value = 1;
|
||||
startHour.value = 0;
|
||||
startMinute.value = 0;
|
||||
startSecond.value = 0;
|
||||
workersValue.value = 1;
|
||||
proxyScheme.value = "off";
|
||||
proxyHost.value = "";
|
||||
proxyPort.value = null;
|
||||
proxyUser.value = "";
|
||||
proxyPassword.value = "";
|
||||
proxyHasPassword.value = false;
|
||||
proxyError.value = "";
|
||||
settingsError.value = "";
|
||||
}
|
||||
|
||||
async function openProxy(ids: string[]) {
|
||||
function applyRowSettings(row: UserRow) {
|
||||
monthlyTarget.value = row.monthly_target;
|
||||
startDay.value = row.study_start_day;
|
||||
startHour.value = row.study_start_hour;
|
||||
startMinute.value = row.study_start_minute;
|
||||
startSecond.value = row.study_start_second;
|
||||
workersValue.value = row.course_workers;
|
||||
}
|
||||
|
||||
async function openSettings(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
proxyIds.value = ids;
|
||||
resetProxyForm();
|
||||
proxyOpen.value = true;
|
||||
settingsIds.value = ids;
|
||||
resetSettingsForm();
|
||||
settingsOpen.value = true;
|
||||
if (ids.length !== 1) return;
|
||||
const row = users.value.find((item) => item.employee_id === ids[0]);
|
||||
if (row) applyRowSettings(row);
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(ids[0])}/proxy`);
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
@@ -382,52 +429,93 @@ async function openProxy(ids: string[]) {
|
||||
function proxyPasswordPayload() {
|
||||
if (proxyPassword.value !== "") return proxyPassword.value;
|
||||
if (!proxyUser.value.trim()) return "";
|
||||
if (proxyIds.value.length === 1 && proxyHasPassword.value) return null;
|
||||
if (settingsIds.value.length === 1 && proxyHasPassword.value) return null;
|
||||
return "";
|
||||
}
|
||||
|
||||
async function saveProxy() {
|
||||
if (proxySaving.value || !proxyIds.value.length) return;
|
||||
proxyError.value = "";
|
||||
async function saveSettings() {
|
||||
if (settingsSaving.value || !settingsIds.value.length) return;
|
||||
settingsError.value = "";
|
||||
if (monthlyTarget.value == null || !Number.isInteger(monthlyTarget.value) || monthlyTarget.value < 0 || monthlyTarget.value > 9999) {
|
||||
settingsError.value = "每月学时目标须为 0 到 9999";
|
||||
return;
|
||||
}
|
||||
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)
|
||||
) {
|
||||
settingsError.value = "请填写完整的开始时刻";
|
||||
return;
|
||||
}
|
||||
if (workersValue.value == null || !Number.isInteger(workersValue.value) || workersValue.value < 1 || workersValue.value > 8) {
|
||||
settingsError.value = "同时学习课程数须为 1 到 8";
|
||||
return;
|
||||
}
|
||||
if (proxyManual.value) {
|
||||
if (!proxyHost.value.trim()) {
|
||||
proxyError.value = "请填写代理地址";
|
||||
settingsError.value = "请填写代理地址";
|
||||
return;
|
||||
}
|
||||
if (proxyPort.value == null || !Number.isInteger(proxyPort.value)) {
|
||||
proxyError.value = "请填写代理端口";
|
||||
settingsError.value = "请填写代理端口";
|
||||
return;
|
||||
}
|
||||
}
|
||||
proxySaving.value = true;
|
||||
settingsSaving.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/proxy", {
|
||||
const response = await fetch("/api/admin/users/study-settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(
|
||||
proxyManual.value
|
||||
? {
|
||||
employee_ids: proxyIds.value,
|
||||
body: JSON.stringify({
|
||||
employee_ids: settingsIds.value,
|
||||
monthly_target: monthlyTarget.value,
|
||||
day: startDay.value,
|
||||
hour: startHour.value,
|
||||
minute: startMinute.value,
|
||||
second: startSecond.value,
|
||||
workers: workersValue.value,
|
||||
scheme: proxyScheme.value,
|
||||
host: proxyHost.value.trim(),
|
||||
port: proxyPort.value,
|
||||
username: proxyUser.value.trim(),
|
||||
password: proxyPasswordPayload(),
|
||||
}
|
||||
: { employee_ids: proxyIds.value, scheme: proxyScheme.value },
|
||||
),
|
||||
password: proxyManual.value ? proxyPasswordPayload() : "",
|
||||
}),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
proxyError.value = detailOf(payload, "没有保存。");
|
||||
settingsError.value = detailOf(payload, "没有保存。");
|
||||
return;
|
||||
}
|
||||
proxyOpen.value = false;
|
||||
settingsOpen.value = false;
|
||||
await load();
|
||||
} catch {
|
||||
proxyError.value = "没有保存。";
|
||||
settingsError.value = "没有保存。";
|
||||
} finally {
|
||||
proxySaving.value = false;
|
||||
settingsSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function setStudy(ids: string[], action: "start" | "stop") {
|
||||
if (!ids.length || studyBusy.value) return;
|
||||
studyBusy.value = true;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/study", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ employee_ids: ids, action }),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, action === "start" ? "没有开始。" : "没有停止。");
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
} catch {
|
||||
errorText.value = action === "start" ? "没有开始。" : "没有停止。";
|
||||
} finally {
|
||||
studyBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,133 +550,28 @@ 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 openWorkers(ids: string[]) {
|
||||
if (!ids.length) return;
|
||||
workersIds.value = ids;
|
||||
workersError.value = "";
|
||||
workersValue.value = 1;
|
||||
if (ids.length === 1) {
|
||||
const row = users.value.find((item) => item.employee_id === ids[0]);
|
||||
if (row) workersValue.value = row.course_workers;
|
||||
}
|
||||
workersOpen.value = true;
|
||||
}
|
||||
|
||||
async function saveWorkers() {
|
||||
if (workersSaving.value || !workersIds.value.length) return;
|
||||
workersError.value = "";
|
||||
if (workersValue.value == null || !Number.isInteger(workersValue.value) || workersValue.value < 1 || workersValue.value > 8) {
|
||||
workersError.value = "同时学习课程数须为 1 到 8";
|
||||
return;
|
||||
}
|
||||
workersSaving.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/course-workers", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
employee_ids: workersIds.value,
|
||||
workers: workersValue.value,
|
||||
}),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
workersError.value = detailOf(payload, "没有保存。");
|
||||
return;
|
||||
}
|
||||
workersOpen.value = false;
|
||||
await load();
|
||||
} catch {
|
||||
workersError.value = "没有保存。";
|
||||
} finally {
|
||||
workersSaving.value = false;
|
||||
}
|
||||
function onMore(key: string | number) {
|
||||
if (key === "check-all") void checkAll();
|
||||
else if (key === "clear-proxy") confirmClearProxy(pickedIds.value);
|
||||
}
|
||||
|
||||
function rowActions(row: UserRow): DropdownOption[] {
|
||||
const busy = checkingAll.value || checkingId.value !== "";
|
||||
const busy = checkingAll.value || checkingId.value !== "" || studyBusy.value;
|
||||
return [
|
||||
{ label: "学习设置", key: "settings" },
|
||||
{ label: row.study_started ? "停止任务" : "立即开始", key: "study", disabled: busy },
|
||||
{ label: "检查", key: "check", disabled: busy },
|
||||
{ label: "查看凭据", key: "credentials" },
|
||||
{ label: "设置代理", key: "proxy" },
|
||||
{ label: "清除代理", key: "proxy-clear" },
|
||||
{ label: "开始时刻", key: "start" },
|
||||
{ label: "同时课程", key: "workers" },
|
||||
{ label: row.refresh_paused ? "恢复自动刷新" : "停止自动刷新", key: "refresh" },
|
||||
{ label: "删除", key: "delete", props: { style: { color: "var(--danger)" } } },
|
||||
];
|
||||
}
|
||||
|
||||
function onRowAction(row: UserRow, key: string | number) {
|
||||
if (key === "check") void checkOne(row);
|
||||
if (key === "settings") void openSettings([row.employee_id]);
|
||||
else if (key === "study") void setStudy([row.employee_id], row.study_started ? "stop" : "start");
|
||||
else if (key === "check") void checkOne(row);
|
||||
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 === "workers") openWorkers([row.employee_id]);
|
||||
else if (key === "refresh") confirmRefresh(row);
|
||||
else if (key === "delete") confirmDelete(row);
|
||||
}
|
||||
@@ -603,11 +586,40 @@ onMounted(() => {
|
||||
<header class="page-head">
|
||||
<h2>用户管理</h2>
|
||||
<div class="page-head-actions">
|
||||
<n-button :disabled="!pickedIds.length" @click="openProxy(pickedIds)">设置代理</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="confirmClearProxy(pickedIds)">清除代理</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="openStart(pickedIds)">开始时刻</n-button>
|
||||
<n-button :disabled="!pickedIds.length" @click="openWorkers(pickedIds)">同时课程</n-button>
|
||||
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle :disabled="!pickedIds.length" aria-label="学习设置" @click="openSettings(pickedIds)">
|
||||
<template #icon><n-icon><SettingsOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
学习设置
|
||||
</n-tooltip>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="立即开始" @click="setStudy(pickedIds, 'start')">
|
||||
<template #icon><n-icon><PlayOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
立即开始
|
||||
</n-tooltip>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="停止任务" @click="setStudy(pickedIds, 'stop')">
|
||||
<template #icon><n-icon><PauseOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
停止任务
|
||||
</n-tooltip>
|
||||
<n-dropdown trigger="click" placement="bottom-end" :options="moreOptions" @select="onMore">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle aria-label="更多">
|
||||
<template #icon><n-icon><EllipsisHorizontalOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
更多
|
||||
</n-tooltip>
|
||||
</n-dropdown>
|
||||
</div>
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
@@ -621,10 +633,9 @@ onMounted(() => {
|
||||
</th>
|
||||
<th>工号</th>
|
||||
<th>凭证</th>
|
||||
<th>凭据是否有效</th>
|
||||
<th>有效</th>
|
||||
<th>本月学时</th>
|
||||
<th>开始时刻</th>
|
||||
<th>同时课程</th>
|
||||
<th>任务</th>
|
||||
<th>代理</th>
|
||||
<th>上次刷新时间</th>
|
||||
<th>自动刷新</th>
|
||||
@@ -640,16 +651,20 @@ onMounted(() => {
|
||||
<td>{{ row.has_credential ? "已保存凭证" : "未保存凭证" }}</td>
|
||||
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
|
||||
<td class="when">{{ row.month_hours || "—" }}</td>
|
||||
<td class="when">{{ row.study_start || "—" }}</td>
|
||||
<td class="when">{{ row.course_workers }}{{ row.course_workers === 1 ? "(推荐)" : "" }}</td>
|
||||
<td :class="row.study_started ? 'ok' : 'quiet'">{{ taskText(row) }}</td>
|
||||
<td class="when">{{ row.proxy || "—" }}</td>
|
||||
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
|
||||
<td>{{ row.refresh_paused ? "已停止" : "开启" }}</td>
|
||||
<td>
|
||||
<n-dropdown trigger="click" placement="bottom-end" :options="rowActions(row)" @select="(key) => onRowAction(row, key)">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button size="small" quaternary circle :aria-label="`工号 ${row.employee_id} 的操作`">
|
||||
<template #icon><n-icon><SettingsOutline /></n-icon></template>
|
||||
<template #icon><n-icon><EllipsisVerticalOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
操作
|
||||
</n-tooltip>
|
||||
</n-dropdown>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -681,95 +696,32 @@ onMounted(() => {
|
||||
</template>
|
||||
</n-modal>
|
||||
<n-modal
|
||||
:show="proxyOpen"
|
||||
:show="settingsOpen"
|
||||
preset="card"
|
||||
:title="proxyIds.length === 1 ? `工号 ${proxyIds[0]} 的代理` : `已选 ${proxyIds.length} 个账号的代理`"
|
||||
:title="settingsIds.length === 1 ? `工号 ${settingsIds[0]} 的学习设置` : `已选 ${settingsIds.length} 个账号的学习设置`"
|
||||
:style="{ width: 'min(520px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (proxyOpen = show)"
|
||||
:content-style="{ maxHeight: 'min(70vh, 560px)', overflow: 'auto' }"
|
||||
@update:show="(show) => (settingsOpen = show)"
|
||||
>
|
||||
<n-alert v-if="proxyError" class="admin-alert" type="error">{{ proxyError }}</n-alert>
|
||||
<form class="settings-form" @submit.prevent="saveProxy">
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-scheme">类型</label>
|
||||
<n-select id="admin-proxy-scheme" v-model:value="proxyScheme" :options="proxyOptions" />
|
||||
<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-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>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-host">地址</label>
|
||||
<n-input id="admin-proxy-host" v-model:value="proxyHost" placeholder="例如 127.0.0.1" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-port">端口</label>
|
||||
<n-input-number id="admin-proxy-port" v-model:value="proxyPort" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-user">账号</label>
|
||||
<n-input id="admin-proxy-user" v-model:value="proxyUser" placeholder="可不填" autocomplete="off" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-proxy-password">密码</label>
|
||||
<n-input
|
||||
id="admin-proxy-password"
|
||||
v-model:value="proxyPassword"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="proxyIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'"
|
||||
autocomplete="new-password"
|
||||
:disabled="!proxyManual"
|
||||
/>
|
||||
</div>
|
||||
</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>
|
||||
<n-modal
|
||||
:show="startOpen"
|
||||
preset="card"
|
||||
:title="startIds.length === 1 ? `工号 ${startIds[0]} 的开始时刻` : `已选 ${startIds.length} 个账号的开始时刻`"
|
||||
:style="{ width: 'min(520px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (startOpen = show)"
|
||||
>
|
||||
<n-alert v-if="startError" class="admin-alert" type="error">{{ startError }}</n-alert>
|
||||
<form class="settings-form" @submit.prevent="saveStart">
|
||||
<div class="form-row">
|
||||
<label for="admin-start-day">每月</label>
|
||||
</n-form-item>
|
||||
<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-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-start-hour">时</label>
|
||||
<n-input-number id="admin-start-hour" v-model:value="startHour" button-placement="both" :min="0" :max="23" :precision="0" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-start-minute">分</label>
|
||||
<n-input-number id="admin-start-minute" v-model:value="startMinute" button-placement="both" :min="0" :max="59" :precision="0" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-start-second">秒</label>
|
||||
<n-input-number id="admin-start-second" v-model:value="startSecond" button-placement="both" :min="0" :max="59" :precision="0" />
|
||||
</div>
|
||||
</form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="startOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="startSaving" @click="saveStart">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
<n-modal
|
||||
:show="workersOpen"
|
||||
preset="card"
|
||||
:title="workersIds.length === 1 ? `工号 ${workersIds[0]} 的同时课程` : `已选 ${workersIds.length} 个账号的同时课程`"
|
||||
:style="{ width: 'min(520px, calc(100vw - 32px))' }"
|
||||
@update:show="(show) => (workersOpen = show)"
|
||||
>
|
||||
<n-alert v-if="workersError" class="admin-alert" type="error">{{ workersError }}</n-alert>
|
||||
<form class="settings-form" @submit.prevent="saveWorkers">
|
||||
<div class="form-row">
|
||||
<label class="field-title" for="admin-course-workers">
|
||||
<span>同时学习</span>
|
||||
</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="说明">
|
||||
@@ -778,15 +730,41 @@ onMounted(() => {
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</label>
|
||||
</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>
|
||||
<p v-if="workersValue === 1" class="form-hint">1 门为推荐</p>
|
||||
</form>
|
||||
</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>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="workersOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="workersSaving" @click="saveWorkers">保存</n-button>
|
||||
<n-button @click="settingsOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="settingsSaving" @click="saveSettings">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
|
||||
@@ -120,9 +120,8 @@ onMounted(refresh);
|
||||
|
||||
<template>
|
||||
<section class="page list-page">
|
||||
<section class="board" aria-labelledby="exam-heading" :aria-busy="state === 'loading'">
|
||||
<h3>
|
||||
<span id="exam-heading">我的考试</span>
|
||||
<header class="page-head">
|
||||
<h2 id="exam-heading">我的考试</h2>
|
||||
<span class="board-tools">
|
||||
<span v-if="state === 'loading'" class="spin" role="status" aria-label="正在获取"></span>
|
||||
<n-tooltip placement="bottom">
|
||||
@@ -132,17 +131,18 @@ onMounted(refresh);
|
||||
quaternary
|
||||
circle
|
||||
size="small"
|
||||
aria-label="刷新数据"
|
||||
aria-label="刷新"
|
||||
:loading="refreshing"
|
||||
@click="refresh"
|
||||
>
|
||||
<template #icon><n-icon><RefreshOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
刷新数据
|
||||
刷新
|
||||
</n-tooltip>
|
||||
</span>
|
||||
</h3>
|
||||
</header>
|
||||
<section class="board" aria-labelledby="exam-heading" :aria-busy="state === 'loading'">
|
||||
<div class="rail" tabindex="0">
|
||||
<n-alert v-if="state === 'error'" class="section-error" type="error">{{ errorText }}</n-alert>
|
||||
<p v-else-if="items && !items.length" class="rail-empty">没有考试</p>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, h, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NDataTable, NIcon, NPagination, NTooltip, type DataTableColumns } from "naive-ui";
|
||||
import { RefreshOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface HistoryItem {
|
||||
title: string;
|
||||
minutes: number | null;
|
||||
studied_at: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
type SectionState = "loading" | "ready" | "error";
|
||||
|
||||
const items = ref<HistoryItem[] | null>(null);
|
||||
const state = ref<SectionState>("loading");
|
||||
const errorText = ref("");
|
||||
const refreshing = ref(false);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const pageSizes = [10, 20, 50];
|
||||
let refreshRunning = false;
|
||||
let busy = false;
|
||||
|
||||
function failureText(payload: { detail?: unknown }, fallback: string) {
|
||||
return typeof payload.detail === "string" ? payload.detail : fallback;
|
||||
}
|
||||
|
||||
function asItem(value: unknown): HistoryItem | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const row = value as Record<string, unknown>;
|
||||
const title = typeof row.title === "string" ? row.title : "";
|
||||
const studied = typeof row.studied_at === "string" ? row.studied_at : "";
|
||||
if (!title && !studied) return null;
|
||||
return {
|
||||
title,
|
||||
minutes: typeof row.minutes === "number" ? row.minutes : null,
|
||||
studied_at: studied,
|
||||
path: typeof row.path === "string" ? row.path : "",
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
const hadData = items.value !== null;
|
||||
if (!hadData) state.value = "loading";
|
||||
try {
|
||||
const response = await fetch("/api/home/history");
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
if (!hadData) {
|
||||
errorText.value = failureText(payload, "学时历史没有获取到。");
|
||||
state.value = "error";
|
||||
}
|
||||
return;
|
||||
}
|
||||
const rows: unknown[] = Array.isArray(payload.items) ? payload.items : [];
|
||||
const parsed: HistoryItem[] = [];
|
||||
for (const row of rows) {
|
||||
const item = asItem(row);
|
||||
if (item) parsed.push(item);
|
||||
}
|
||||
items.value = parsed;
|
||||
errorText.value = "";
|
||||
state.value = "ready";
|
||||
const maxPage = Math.max(1, Math.ceil(parsed.length / pageSize.value));
|
||||
if (page.value > maxPage) page.value = maxPage;
|
||||
} catch {
|
||||
if (!hadData) {
|
||||
errorText.value = "学时历史没有获取到。";
|
||||
state.value = "error";
|
||||
}
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
if (refreshRunning) return;
|
||||
refreshRunning = true;
|
||||
refreshing.value = true;
|
||||
void load().finally(() => {
|
||||
refreshRunning = false;
|
||||
refreshing.value = false;
|
||||
});
|
||||
}
|
||||
|
||||
const paged = computed(() => {
|
||||
const rows = items.value ?? [];
|
||||
const start = (page.value - 1) * pageSize.value;
|
||||
return rows.slice(start, start + pageSize.value);
|
||||
});
|
||||
|
||||
const columns: DataTableColumns<HistoryItem> = [
|
||||
{
|
||||
title: "来源",
|
||||
key: "title",
|
||||
ellipsis: { tooltip: true },
|
||||
render(row) {
|
||||
return h("span", { class: "history-title", title: row.title }, row.title || "—");
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "获得学时(分钟)",
|
||||
key: "minutes",
|
||||
width: 160,
|
||||
align: "right",
|
||||
render(row) {
|
||||
return row.minutes == null ? "—" : String(row.minutes);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "日期",
|
||||
key: "studied_at",
|
||||
width: 180,
|
||||
render(row) {
|
||||
return row.studied_at || "—";
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function goPage(next: number) {
|
||||
page.value = next;
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size;
|
||||
page.value = 1;
|
||||
}
|
||||
|
||||
onMounted(refresh);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page list-page history-page">
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>学时历史</h2>
|
||||
<p v-if="items">共 {{ items.length }} 条</p>
|
||||
</div>
|
||||
<n-tooltip placement="bottom">
|
||||
<template #trigger>
|
||||
<n-button
|
||||
class="home-refresh"
|
||||
quaternary
|
||||
circle
|
||||
size="small"
|
||||
aria-label="刷新"
|
||||
:loading="refreshing"
|
||||
@click="refresh"
|
||||
>
|
||||
<template #icon><n-icon><RefreshOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
刷新
|
||||
</n-tooltip>
|
||||
</header>
|
||||
<n-alert v-if="state === 'error'" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<div class="history-table">
|
||||
<n-data-table
|
||||
v-if="state !== 'error'"
|
||||
:columns="columns"
|
||||
:data="state === 'loading' ? [] : paged"
|
||||
:loading="state === 'loading' || refreshing"
|
||||
:bordered="false"
|
||||
:single-line="false"
|
||||
:scroll-x="720"
|
||||
:row-key="(row: HistoryItem) => `${row.studied_at}-${row.title}-${row.path}`"
|
||||
/>
|
||||
<p v-else-if="!errorText" class="admin-status">没有学时记录</p>
|
||||
</div>
|
||||
<n-pagination
|
||||
v-if="items && items.length"
|
||||
class="course-pager"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
:item-count="items.length"
|
||||
:page-sizes="pageSizes"
|
||||
show-size-picker
|
||||
show-quick-jumper
|
||||
@update:page="goPage"
|
||||
@update:page-size="changeSize"
|
||||
>
|
||||
<template #prefix="{ itemCount }">共 {{ itemCount }} 条</template>
|
||||
</n-pagination>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInput, NInputNumber, NSelect, NTooltip } from "naive-ui";
|
||||
import { HelpCircleOutline, RefreshOutline } from "@vicons/ionicons5";
|
||||
import { NAlert, NButton, NForm, NFormItem, NIcon, NInput, NInputNumber, NSelect, NTimePicker, NTooltip } from "naive-ui";
|
||||
import { HelpCircleOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
|
||||
|
||||
interface HomeSummary {
|
||||
name: string;
|
||||
@@ -41,12 +41,39 @@ const studyStatus = ref<{
|
||||
message: string;
|
||||
} | null>(null);
|
||||
|
||||
const studyControl = ref({
|
||||
started: false,
|
||||
paused: false,
|
||||
ignore_window: false,
|
||||
window_open: false,
|
||||
active: false,
|
||||
state: "",
|
||||
course: "",
|
||||
});
|
||||
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;
|
||||
if (state === "已达标") return "本月目标已达到";
|
||||
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
|
||||
if (studyControl.value.active || live) {
|
||||
return `正在学习:${course || state || "准备中"}`;
|
||||
}
|
||||
if (studyControl.value.started) return "任务已开始,等待执行";
|
||||
if (studyStatus.value?.message) return studyStatus.value.message;
|
||||
if (studyStatus.value?.running) return "自动学习进行中";
|
||||
return "未到开始时间";
|
||||
});
|
||||
|
||||
function amount(value: string | number | null | undefined) {
|
||||
if (value === null || value === undefined || value === "") return "—";
|
||||
const numeric = Number(value);
|
||||
@@ -71,6 +98,10 @@ function failureText(payload: { detail?: unknown }, fallback: string) {
|
||||
return typeof payload.detail === "string" ? payload.detail : fallback;
|
||||
}
|
||||
|
||||
function pad(value: number) {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
@@ -103,7 +134,7 @@ function refresh() {
|
||||
if (refreshRunning) return;
|
||||
refreshRunning = true;
|
||||
refreshing.value = true;
|
||||
void loadSummary().finally(() => {
|
||||
void Promise.all([loadSummary(), loadStudyStatus(), loadStudyControl()]).finally(() => {
|
||||
refreshRunning = false;
|
||||
refreshing.value = false;
|
||||
});
|
||||
@@ -143,6 +174,20 @@ const startMinute = ref<number | null>(0);
|
||||
const startSecond = ref<number | null>(0);
|
||||
let startSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const startTime = computed({
|
||||
get() {
|
||||
return `${pad(startHour.value ?? 0)}:${pad(startMinute.value ?? 0)}:${pad(startSecond.value ?? 0)}`;
|
||||
},
|
||||
set(value: string | null) {
|
||||
if (!value) return;
|
||||
const [hour, minute, second] = value.split(":").map((part) => Number(part));
|
||||
if (![hour, minute, second].every((part) => Number.isInteger(part))) return;
|
||||
startHour.value = hour;
|
||||
startMinute.value = minute;
|
||||
startSecond.value = second;
|
||||
},
|
||||
});
|
||||
|
||||
async function loadStart() {
|
||||
try {
|
||||
const res = await fetch("/api/settings/study-start");
|
||||
@@ -308,13 +353,64 @@ async function loadStudyStatus() {
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy(); loadStudyStatus(); });
|
||||
function applyStudyControl(payload: Record<string, unknown>) {
|
||||
studyControl.value = {
|
||||
started: payload.started === true,
|
||||
paused: payload.paused === true,
|
||||
ignore_window: payload.ignore_window === true,
|
||||
window_open: payload.window_open === true,
|
||||
active: payload.active === true,
|
||||
state: typeof payload.state === "string" ? payload.state : "",
|
||||
course: typeof payload.course === "string" ? payload.course : "",
|
||||
};
|
||||
}
|
||||
|
||||
async function loadStudyControl() {
|
||||
try {
|
||||
const res = await fetch("/api/settings/study-control");
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok) applyStudyControl(data);
|
||||
} catch { /* 静默 */ }
|
||||
}
|
||||
|
||||
async function toggleStudy() {
|
||||
if (studyBusy.value) return;
|
||||
studyBusy.value = true;
|
||||
studyError.value = "";
|
||||
const action = studyControl.value.started ? "stop" : "start";
|
||||
try {
|
||||
const res = await fetch("/api/settings/study-control", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
studyError.value = failureText(data, action === "start" ? "没有开始。" : "没有停止。");
|
||||
return;
|
||||
}
|
||||
applyStudyControl(data);
|
||||
await loadStudyStatus();
|
||||
} catch {
|
||||
studyError.value = action === "start" ? "没有开始。" : "没有停止。";
|
||||
} finally {
|
||||
studyBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
refresh();
|
||||
loadTarget();
|
||||
loadStart();
|
||||
loadWorkers();
|
||||
loadProxy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page home-page">
|
||||
<div class="home">
|
||||
<div class="home-summary" :aria-busy="summaryState === 'loading'">
|
||||
<section class="panel-card home-summary" :aria-busy="summaryState === 'loading'">
|
||||
<div class="home-top">
|
||||
<div class="home-top-main">
|
||||
<n-alert v-if="summaryState === 'error'" class="summary-error" type="error">{{ summaryError }}</n-alert>
|
||||
@@ -363,9 +459,26 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div v-if="targetLoaded" class="home-target">
|
||||
<label for="monthly-target">每月自动学习目标</label>
|
||||
</section>
|
||||
|
||||
<section class="panel-card">
|
||||
<header class="panel-card-head">
|
||||
<h3>自动学习</h3>
|
||||
<n-button
|
||||
:type="studyControl.started ? 'error' : 'primary'"
|
||||
size="small"
|
||||
:loading="studyBusy"
|
||||
@click="toggleStudy"
|
||||
>
|
||||
<template #icon>
|
||||
<n-icon><StopOutline v-if="studyControl.started" /><PlayOutline v-else /></n-icon>
|
||||
</template>
|
||||
{{ studyControl.started ? "停止" : "立即开始" }}
|
||||
</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-item v-if="targetLoaded" label="每月目标">
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="monthly-target"
|
||||
@@ -378,22 +491,18 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
|
||||
/>
|
||||
<span class="target-unit">分钟</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="startLoaded" class="home-target home-start">
|
||||
<label for="study-start-day">每月开始学习</label>
|
||||
</n-form-item>
|
||||
<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-input-number v-model:value="startHour" button-placement="both" :min="0" :max="23" :precision="0" size="small" />
|
||||
<span class="target-unit">:</span>
|
||||
<n-input-number v-model:value="startMinute" button-placement="both" :min="0" :max="59" :precision="0" size="small" />
|
||||
<span class="target-unit">:</span>
|
||||
<n-input-number v-model:value="startSecond" button-placement="both" :min="0" :max="59" :precision="0" size="small" />
|
||||
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" size="small" :actions="null" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="workersLoaded" class="home-target">
|
||||
<label class="field-title" for="course-workers">
|
||||
<span>同时学习课程</span>
|
||||
</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="说明">
|
||||
@@ -402,7 +511,8 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
|
||||
</template>
|
||||
速度较慢,但是稳定且不容易触发风控,最大可设置8
|
||||
</n-tooltip>
|
||||
</label>
|
||||
</span>
|
||||
</template>
|
||||
<div class="target-control">
|
||||
<n-input-number
|
||||
id="course-workers"
|
||||
@@ -416,29 +526,35 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
|
||||
<span class="target-unit">门</span>
|
||||
<span v-if="courseWorkers === 1" class="recommend-mark">推荐</span>
|
||||
</div>
|
||||
</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>
|
||||
<form v-if="proxyLoaded" class="home-proxy" @submit.prevent="saveProxy">
|
||||
</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>
|
||||
<div class="form-row">
|
||||
<label for="proxy-scheme">代理类型</label>
|
||||
<n-select id="proxy-scheme" v-model:value="proxyScheme" size="small" :options="proxyOptions" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-host">代理地址</label>
|
||||
<n-input id="proxy-host" v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-port">代理端口</label>
|
||||
<n-input-number id="proxy-port" v-model:value="proxyPort" size="small" button-placement="both" :min="1" :max="65535" :precision="0" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-user">代理账号</label>
|
||||
<n-input id="proxy-user" v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" :disabled="!proxyManual" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="proxy-password">代理密码</label>
|
||||
<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>
|
||||
<n-form-item label="地址">
|
||||
<n-input v-model:value="proxyHost" size="small" placeholder="例如 127.0.0.1" :disabled="!proxyManual" />
|
||||
</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-form-item>
|
||||
<n-form-item label="账号">
|
||||
<n-input v-model:value="proxyUser" size="small" placeholder="可不填" autocomplete="off" :disabled="!proxyManual" />
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input
|
||||
id="proxy-password"
|
||||
v-model:value="proxyPassword"
|
||||
size="small"
|
||||
type="password"
|
||||
@@ -447,20 +563,9 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
|
||||
autocomplete="new-password"
|
||||
:disabled="!proxyManual"
|
||||
/>
|
||||
</div>
|
||||
<div class="home-proxy-actions">
|
||||
<n-button type="primary" size="small" attr-type="submit" :loading="proxySaving">保存</n-button>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</form>
|
||||
<div v-if="studyStatus" class="home-study-status">
|
||||
<span class="study-indicator" :class="{ active: Boolean(myStudy) || studyStatus.running }"></span>
|
||||
<span v-if="myStudy" class="study-text">
|
||||
{{ myStudy.state === "已达标" ? "本月目标已达到" : `正在学习:${myStudy.course || myStudy.state || "准备中"}` }}
|
||||
</span>
|
||||
<span v-else-if="studyStatus.running" class="study-text muted">自动学习进行中</span>
|
||||
<span v-else-if="studyStatus.message" class="study-text muted">{{ studyStatus.message }}</span>
|
||||
<span v-else class="study-text muted">自动学习未运行</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -136,9 +136,8 @@ onMounted(refresh);
|
||||
|
||||
<template>
|
||||
<section class="page list-page">
|
||||
<section class="board" aria-labelledby="training-heading" :aria-busy="state === 'loading'">
|
||||
<h3>
|
||||
<span id="training-heading">线上培训</span>
|
||||
<header class="page-head">
|
||||
<h2 id="training-heading">线上培训</h2>
|
||||
<span class="board-tools">
|
||||
<span v-if="state === 'loading'" class="spin" role="status" aria-label="正在获取"></span>
|
||||
<n-tooltip placement="bottom">
|
||||
@@ -148,17 +147,18 @@ onMounted(refresh);
|
||||
quaternary
|
||||
circle
|
||||
size="small"
|
||||
aria-label="刷新数据"
|
||||
aria-label="刷新"
|
||||
:loading="refreshing"
|
||||
@click="refresh"
|
||||
>
|
||||
<template #icon><n-icon><RefreshOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
刷新数据
|
||||
刷新
|
||||
</n-tooltip>
|
||||
</span>
|
||||
</h3>
|
||||
</header>
|
||||
<section class="board" aria-labelledby="training-heading" :aria-busy="state === 'loading'">
|
||||
<div class="rail" tabindex="0">
|
||||
<n-alert v-if="state === 'error'" class="section-error" type="error">{{ errorText }}</n-alert>
|
||||
<p v-else-if="items && !items.length" class="rail-empty">没有线上培训</p>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons
|
||||
import { isDark, toggleTheme } from "../shared/theme";
|
||||
import { navOptions, type PageKey } from "./navigation";
|
||||
import HomeView from "../features/home/HomeView.vue";
|
||||
import HoursHistoryView from "../features/history/HoursHistoryView.vue";
|
||||
import ExamsView from "../features/exams/ExamsView.vue";
|
||||
import TrainingsView from "../features/trainings/TrainingsView.vue";
|
||||
|
||||
@@ -15,7 +16,7 @@ const collapsed = ref(window.innerWidth < 800);
|
||||
|
||||
function pageFromHash(): PageKey {
|
||||
const name = window.location.hash.replace(/^#\/?/, "");
|
||||
if (name === "exams" || name === "trainings" || name === "home") return name;
|
||||
if (name === "exams" || name === "trainings" || name === "history" || name === "home") return name;
|
||||
return "home";
|
||||
}
|
||||
|
||||
@@ -48,7 +49,7 @@ const logoutOptions = [
|
||||
];
|
||||
|
||||
function onMenu(key: string) {
|
||||
if (key === "home" || key === "exams" || key === "trainings") {
|
||||
if (key === "home" || key === "history" || key === "exams" || key === "trainings") {
|
||||
page.value = key;
|
||||
remember(key);
|
||||
}
|
||||
@@ -111,6 +112,7 @@ function onLogout(key: string) {
|
||||
</n-layout-sider>
|
||||
<n-layout class="content" :native-scrollbar="false" content-style="height: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column;">
|
||||
<HomeView v-if="page === 'home'" :employee-id="props.employeeId" />
|
||||
<HoursHistoryView v-else-if="page === 'history'" />
|
||||
<ExamsView v-else-if="page === 'exams'" />
|
||||
<TrainingsView v-else />
|
||||
</n-layout>
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import type { Component } from "vue";
|
||||
import { h } from "vue";
|
||||
import { NIcon } from "naive-ui";
|
||||
import { HomeOutline, ReaderOutline, SchoolOutline } from "@vicons/ionicons5";
|
||||
import { HomeOutline, ReaderOutline, SchoolOutline, TimeOutline } from "@vicons/ionicons5";
|
||||
|
||||
function renderIcon(icon: Component) {
|
||||
return () => h(NIcon, null, { default: () => h(icon) });
|
||||
}
|
||||
|
||||
export type PageKey = "home" | "exams" | "trainings";
|
||||
export type PageKey = "home" | "history" | "exams" | "trainings";
|
||||
|
||||
export const navOptions = [
|
||||
{ label: "首页", key: "home" as const, icon: renderIcon(HomeOutline) },
|
||||
{ label: "学时历史", key: "history" as const, icon: renderIcon(TimeOutline) },
|
||||
{ label: "我的考试", key: "exams" as const, icon: renderIcon(ReaderOutline) },
|
||||
{ label: "线上培训", key: "trainings" as const, icon: renderIcon(SchoolOutline) },
|
||||
];
|
||||
|
||||
+127
-44
@@ -327,9 +327,14 @@ select {
|
||||
|
||||
.page-head {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.page-head h2 {
|
||||
@@ -360,6 +365,102 @@ select {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.panel-card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.panel-card > h3 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.panel-card-head h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.panel-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.compact-form,
|
||||
.compact-nform {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 560px;
|
||||
}
|
||||
|
||||
.compact-nform.n-form {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item {
|
||||
margin: 0;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item-label {
|
||||
white-space: nowrap;
|
||||
padding-right: 12px !important;
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item-blank {
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.compact-nform .n-form-item-feedback-wrapper {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.compact-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.compact-row > label,
|
||||
.compact-row > .field-title,
|
||||
.field-title {
|
||||
flex: none;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.compact-row > .n-select,
|
||||
.compact-row > .n-input,
|
||||
.compact-row > .n-input-number,
|
||||
.compact-row > .n-time-picker {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.settings-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
.settings-stack .form-hint {
|
||||
margin: 0 0 4px 188px;
|
||||
}
|
||||
|
||||
.list-page {
|
||||
@@ -376,10 +477,6 @@ select {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.home-summary .facts {
|
||||
@@ -461,50 +558,21 @@ select {
|
||||
width: 88px;
|
||||
}
|
||||
|
||||
.start-control .n-time-picker {
|
||||
width: 148px;
|
||||
}
|
||||
|
||||
.target-unit {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.home-proxy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.home-proxy .form-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.home-proxy .form-row label {
|
||||
flex: none;
|
||||
width: 84px;
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.home-proxy .form-row .n-select,
|
||||
.home-proxy .form-row .n-input,
|
||||
.home-proxy .form-row .n-input-number {
|
||||
flex: 1;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.home-proxy-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding-left: 96px;
|
||||
}
|
||||
|
||||
.home-study-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-top: 12px;
|
||||
padding-top: 8px;
|
||||
margin-top: 4px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
@@ -1056,13 +1124,13 @@ select {
|
||||
}
|
||||
|
||||
.settings-form .form-row {
|
||||
grid-template-columns: max-content minmax(160px, 280px);
|
||||
grid-template-columns: 7.5em minmax(160px, 280px);
|
||||
justify-content: start;
|
||||
}
|
||||
|
||||
.settings-form .form-row label {
|
||||
min-width: 15em;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
@@ -1093,11 +1161,26 @@ select {
|
||||
|
||||
.form-hint {
|
||||
margin: 0;
|
||||
padding: 2px 0 0 160px;
|
||||
padding: 2px 0 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.history-table {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.history-title {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.n-data-table {
|
||||
--n-merged-th-color: transparent;
|
||||
--n-merged-td-color: transparent;
|
||||
}
|
||||
|
||||
.page-head-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
Reference in New Issue
Block a user