diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 6b2eb16..8a0b6d9 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -12,7 +12,15 @@ from pydantic import BaseModel, Field from sqlalchemy.orm import Session from euniv.db import get_db, init_db -from euniv.service import fetch_home, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw +from euniv.service import ( + fetch_exam_detail, + fetch_home, + fetch_training_detail, + login_and_store, + revoke_credential, + start_credential_refresh, + submit_jigsaw, +) from euniv.session import clear_session, read_employee_id, write_session @@ -95,13 +103,33 @@ def revoke(request: Request, response: Response, db: Session = Depends(get_db)) return {"ok": True} -@app.get("/api/home") -def home(request: Request, db: Session = Depends(get_db)) -> dict: +def _signed_in(request: Request) -> str: employee_id = read_employee_id(request.cookies) if not employee_id: raise HTTPException(status_code=401, detail="未登录") + return employee_id + + +@app.get("/api/home") +def home(request: Request, db: Session = Depends(get_db)) -> dict: try: - return fetch_home(db, employee_id) + return fetch_home(db, _signed_in(request)) + except RuntimeError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@app.get("/api/exam") +def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict: + try: + return fetch_exam_detail(db, _signed_in(request), path) + 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: + return fetch_training_detail(db, _signed_in(request), path) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc diff --git a/backend/euniv/client.py b/backend/euniv/client.py index ed0872f..c8b892c 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -9,6 +9,7 @@ import re import time import uuid from datetime import datetime +from html import unescape from urllib.parse import quote import httpx @@ -86,6 +87,7 @@ def parse_training_cards(page: str, status: str) -> list[dict]: owner = re.search(r'\s*([^<]+)', block) assigned = re.search(r"sty_lbl_assignedtime\">([^<]+)", block) credits = re.search(r"el-plan-time'>([^<]+)", block) + detail = re.search(r"""learningKnowledge\(['"](/plan/[0-9a-fA-F]{32}\.html)['"]\)""", block) assigned_text = "" if assigned: assigned_text = assigned.group(1).replace(" ", " ").replace("\xa0", " ").strip() @@ -96,6 +98,7 @@ def parse_training_cards(page: str, status: str) -> list[dict]: "owner": (owner.group(1).strip() if owner else ""), "assigned": assigned_text, "credits": (credits.group(1).strip() if credits else ""), + "detail": detail.group(1) if detail else "", "sort_days": _leading_number(assigned_text), }) return items @@ -105,18 +108,129 @@ def parse_exam_cards(page: str) -> list[dict]: items = [] for block in re.findall(r'
  • [\s\S]*?
  • ', page): name = re.search(r'class="my-exam-title ellipsis">([^<]+)', block) - status = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', block) + status_match = re.search(r'my-exam-btn[^"]*"[^>]*value="([^"]+)"', block) start = re.search(r'sty_lbl_teststarttime">
    :([^<&]+)', block) + link = re.search(r'href="(/exam/exampreview\.htm\?[^"]+)"', block) + status = status_match.group(1).strip() if status_match else "" start_text = start.group(1).replace(" ", " ").strip() if start else "" + detail = unescape(link.group(1)) if link else "" + if not _exam_detail_path(detail): + detail = "" items.append({ "name": (name.group(1).strip() if name else ""), - "status": (status.group(1).strip() if status else ""), + "status": status, + "result": _exam_result(block, status), "start": start_text, + "detail": detail, "sort_at": _clock_distance(start_text), }) return items +def parse_exam_detail(page: str) -> dict: + if 'id="lblExamName"' not in page: + raise RuntimeError("考试明细没有获取到") + table = re.search(r'class="mt15 exam-history-table"[\s\S]*?', page) + attempts = [] + if table: + for row in re.findall(r"([\s\S]*?)", table.group(0))[1:]: + cells = [_plain(cell) for cell in re.findall(r"]*>([\s\S]*?)", row)] + if len(cells) >= 3 and cells[2] in {"通过", "未通过"}: + attempts.append({"submitted": cells[0], "score": cells[1], "result": cells[2]}) + return { + "name": _field(page, "lblExamName"), + "total_score": _field(page, "lblMaxScore"), + "pass_score": _field(page, "lblPassScore"), + "questions": _field(page, "lblTotalQuestionQty"), + "window": _field(page, "lblControlDateTime"), + "times": _field(page, "lblExamTimes"), + "limit": _field(page, "lblExamLimit"), + "examinee": _field(page, "lblUserName"), + "view_policy": _field(page, "lblViewRestrict"), + "notice": _field(page, "lblMsg"), + "attempts": attempts, + } + + +def parse_training_detail(page: str) -> dict: + if "plandetailhead" not in page: + raise RuntimeError("培训明细没有获取到") + head = page.split('id="knowledgestudy"', 1)[0] + title = re.search(r'class="mb20 span-24 font-size-20">[\s\S]*?([\s\S]*?)\s*\s*', head) + progress = re.search(r'class="schedule1 floatleft">\s*([^<]+)', head) + deadline = re.search(r'mgt_lbl_requirecompletedate">\s*\s*:\s*([^<\s]+)', head) + credits = re.findall(r">\s*([0-9]+(?:\.[0-9]+)?)\s*', page)[1:]: + phase_name = re.search(r'[\s\S]*?([^<]+)', table) + phase_hours = re.search(r":\s*([0-9]+(?:\.[0-9]+)?)\s*[\s\S]*?:\s*([0-9]+(?:\.[0-9]+)?)', table) + tasks = [] + for row in re.findall(r'', table): + task_name = re.search(r"""(\d+%)<", row) + score = re.search( + r'title="已获学分">\s*([^<]+?)\s*\s* /\s* \s*\s*([^<]+)', + row, + ) + hours = re.search( + r'core_lbl_knghours">:\s*([^<&]+?)\s* /\s* \s*([^<&]+?)\s*<', + row, + ) + tasks.append({ + "name": task_name.group(2).strip() if task_name else "", + "progress": percents[-1] if percents else "", + "score": f"{score.group(1).strip()}/{score.group(2).strip()}" if score else "", + "hours": f"{hours.group(1).strip()}/{hours.group(2).strip()}" if hours else "", + }) + phases.append({ + "name": phase_name.group(1).strip() if phase_name else "", + "hours": phase_hours.group(1) if phase_hours else "", + "credits": phase_credits.group(1) if phase_credits else "", + "tasks": tasks, + }) + return { + "name": title.group(1).strip() if title else "", + "owner": _field(head, "lblCertificate"), + "earned_hours": _field(head, "Span1"), + "actual_hours": _field(head, "lblTotalScore"), + "reward_hours": _field(head, "lblPassScore"), + "earned_credits": credits[0] if len(credits) > 0 else "", + "actual_credits": credits[1] if len(credits) > 1 else "", + "reward_credits": credits[2] if len(credits) > 2 else "", + "rank": _plain(rank.group(1)) if rank else "", + "progress": progress.group(1).strip() if progress else "", + "deadline": deadline.group(1) if deadline else "", + "phases": phases, + } + + +def _exam_result(block: str, status: str) -> str: + state = re.search(r"my-exam-state\s+([A-Za-z]+)", block) + if state and state.group(1).lower() == "pass": + return "已通过" + if state and state.group(1).lower() in {"notpass", "nopass", "fail", "unpass"}: + return "未通过" + if status in {"已完成", "已过期", "未参考"}: + return "未通过" + return "" + + +def _exam_detail_path(value: str) -> bool: + return bool(re.fullmatch(r"/exam/exampreview\.htm\?[A-Za-z0-9_=&%.\-]+", value)) and "xamArrangeID=" in value + + +def _field(page: str, element_id: str) -> str: + match = re.search(rf'id="{re.escape(element_id)}"[^>]*>([\s\S]*?)', page) + return _plain(match.group(1)) if match else "" + + +def _plain(value: str) -> str: + text = re.sub(r"<[^>]+>", " ", value) + return re.sub(r"\s+", " ", text).replace("\xa0", " ").replace(" ", " ").strip() + + def _leading_number(value: str) -> float: match = re.search(r"(\d+)", value) return float(match.group(1)) if match else float("inf") @@ -571,6 +685,24 @@ class EunivClient: html = self.client.post(url, data=form, headers=headers).text return self._pages(url, headers, html, parse_exam_cards, "start") + def exam_detail(self, path: str) -> dict: + if not _exam_detail_path(path): + raise RuntimeError("考试明细无法打开") + return parse_exam_detail(self._site_page(path)) + + def training_detail(self, path: str) -> dict: + if not re.fullmatch(r"/plan/[0-9a-fA-F]{32}\.html", path): + raise RuntimeError("培训明细无法打开") + return parse_training_detail(self._site_page(path)) + + def _site_page(self, path: str) -> str: + self._ensure_site() + response = self.client.get( + f"{EUNIV}{path}", + headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, + ) + return response.text + def credential_alive(self) -> bool: try: response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"") diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 95830b5..83343f2 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -122,6 +122,18 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict: """向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。""" + return _live(db, employee_id, client_factory, lambda client: client.home_snapshot()) + + +def fetch_exam_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict: + return _live(db, employee_id, client_factory, lambda client: client.exam_detail(path)) + + +def fetch_training_detail(db: Session, employee_id: str, path: str, client_factory=EunivClient) -> dict: + return _live(db, employee_id, client_factory, lambda client: client.training_detail(path)) + + +def _live(db: Session, employee_id: str, client_factory, read): account = db.get(Account, employee_id) if account is None: raise RuntimeError("请先登录") @@ -136,13 +148,13 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None try: - data = client.home_snapshot() + data = read(client) except SessionExpired: try: client.authorize(client.login()) except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None - data = client.home_snapshot() + data = read(client) updated = client.export_credential() if _dump(updated) != _dump(credential): account.credential_cipher = encrypt_secret(_dump(updated)) diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index c036024..df3647a 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -266,7 +266,7 @@ def test_parse_training_cards_keeps_status() -> None: from euniv.client import parse_training_cards html = """ -
  • +
  • 租赁人员数据保护合规培训-2026
    @@ -283,6 +283,7 @@ def test_parse_training_cards_keeps_status() -> None: "owner": "Jiang Mingjun", "assigned": "194 天", "credits": "1", + "detail": "/plan/1de517c30125424e97840b5cd6f28709.html", "sort_days": 194.0, }] @@ -314,3 +315,80 @@ def test_lists_put_the_nearest_time_first() -> None: "sort_days", ) assert [item["name"] for item in trainings] == ["刚指派", "很久以前"] + assert rows[0]["result"] == "未通过" + assert rows[1]["result"] == "未通过" + + +def test_exam_and_training_details() -> None: + from euniv.client import parse_exam_cards, parse_exam_detail, parse_training_detail + + cards = parse_exam_cards(""" +
  • + 规范考试 + + + :2026-05-20 00:01:00  +
  • + """) + assert cards[0]["result"] == "已通过" + assert cards[0]["detail"] == "/exam/exampreview.htm?examID=abc&examArrangeID=def" + detail = parse_exam_detail(""" + 规范考试 + 100 + 90 + 45 + 2026-05-20 00:01~2026-05-25 23:59 + 2/3 次 + 30分钟 + 莫英达 + 不允许查看答卷详情 + 考试安排已结束 + + + + +
    时间成绩结果
    2026-05-22 16:19:4994通过
    2026-05-22 16:02:1389未通过
    + """) + assert detail["pass_score"] == "90" + assert detail["attempts"] == [ + {"submitted": "2026-05-22 16:19:49", "score": "94", "result": "通过"}, + {"submitted": "2026-05-22 16:02:13", "score": "89", "result": "未通过"}, + ] + training = parse_training_detail(""" +
    +
    安全规范
    + - + 123 + 123 + 0 + 0 + 0 + 0 + +
    100%
    + :2026-11-25 +
    +
    + + + + + + + +
    1规范学习:123 + :12.3
    1.1分享.mp4 + 0 / 5.2 + :52 / 52 + 100% +
    +
    + """) + assert training["rank"] == "2846" + assert training["deadline"] == "2026-11-25" + assert training["phases"][0]["tasks"][0] == { + "name": "1.1分享.mp4", + "progress": "100%", + "score": "0/5.2", + "hours": "52/52", + } diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 45121e0..ada5b14 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -1,11 +1,13 @@