feat: 考试和培训可点开明细,考试列表显示是否通过

This commit is contained in:
2026-10-27 05:48:57 +08:00
parent 84772c9f7a
commit d42691aebb
6 changed files with 538 additions and 24 deletions
+32 -4
View File
@@ -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
+134 -2
View File
@@ -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'<span class="mr10">\s*([^<]+)', block)
assigned = re.search(r"sty_lbl_assignedtime\"><span>([^<]+)", block)
credits = re.search(r"el-plan-time'><span>([^<]+)", block)
detail = re.search(r"""learningKnowledge\(['"](/plan/[0-9a-fA-F]{32}\.html)['"]\)""", block)
assigned_text = ""
if assigned:
assigned_text = assigned.group(1).replace("&nbsp;", " ").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'<li name="userExam">[\s\S]*?</li>', 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"></span>:([^<&]+)', 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("&nbsp;", " ").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]*?</table>', page)
attempts = []
if table:
for row in re.findall(r"<tr>([\s\S]*?)</tr>", table.group(0))[1:]:
cells = [_plain(cell) for cell in re.findall(r"<td\b[^>]*>([\s\S]*?)</td>", 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]*?<span title="([^"]+)"', head)
rank = re.search(r'sty_lbl_ranknumber">([\s\S]*?)</label>\s*</label>\s*</label>', head)
progress = re.search(r'class="schedule1 floatleft">\s*([^<]+)', head)
deadline = re.search(r'mgt_lbl_requirecompletedate">\s*</label>\s*:\s*([^<\s]+)', head)
credits = re.findall(r">\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_point\"", head)
phases = []
for table in re.split(r'<th width="30"><span class="el-mixtrain-num">', page)[1:]:
phase_name = re.search(r'<th class="text-left">[\s\S]*?<span>([^<]+)</span>', table)
phase_hours = re.search(r":\s*([0-9]+(?:\.[0-9]+)?)\s*<span\s+data-localize=\"sty_lbl_minute\"", table)
phase_credits = re.search(r'common_lbl_totalscore"></span>[\s\S]*?:\s*([0-9]+(?:\.[0-9]+)?)', table)
tasks = []
for row in re.findall(r'<tr class="hand"[\s\S]*?</tr>', table):
task_name = re.search(r"""<span class="st" title=(['"])(.*?)\1""", row)
percents = re.findall(r">(\d+%)<", row)
score = re.search(
r'title="已获学分">\s*([^<]+?)\s*</span>\s*&nbsp;/\s*&nbsp;\s*<span class="fontnumber"\s+title="标准学分">\s*([^<]+)',
row,
)
hours = re.search(
r'core_lbl_knghours"></span>:\s*([^<&]+?)\s*&nbsp;/\s*&nbsp;\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]*?)</span>', 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("&nbsp;", " ").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"")
+14 -2
View File
@@ -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))
+79 -1
View File
@@ -266,7 +266,7 @@ def test_parse_training_cards_keeps_status() -> None:
from euniv.client import parse_training_cards
html = """
<li class='el-plan-li-3' id="contentitem1" onclick='learningKnowledge("/plan/a.html")'>
<li class='el-plan-li-3' id="contentitem1" onclick='learningKnowledge("/plan/1de517c30125424e97840b5cd6f28709.html")'>
<div class="el-plan-circle-progress p5" progress="100" id="demo1"></div>
<div class="font-size-16 text-color6 ellipsis">
租赁人员数据保护合规培训-2026</div>
@@ -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("""
<li name="userExam">
<a href="/exam/exampreview.htm?examID=abc&amp;examArrangeID=def" class="my-exam-title ellipsis">规范考试</a>
<span class='my-exam-state pass '></span>
<input class="my-exam-btn" onclick="" value="已完成" />
<span data-localize="sty_lbl_teststarttime"></span>:2026-05-20 00:01:00&nbsp;
</li>
""")
assert cards[0]["result"] == "已通过"
assert cards[0]["detail"] == "/exam/exampreview.htm?examID=abc&examArrangeID=def"
detail = parse_exam_detail("""
<span id="lblExamName">规范考试</span>
<span id="lblMaxScore">100</span>
<span id="lblPassScore">90</span>
<span id="lblTotalQuestionQty">45</span>
<span id="lblControlDateTime">2026-05-20 00:01~2026-05-25 23:59</span>
<span id="lblExamTimes">2/3 次</span>
<span id="lblExamLimit">30分钟</span>
<span id="lblUserName">莫英达</span>
<span id="lblViewRestrict">不允许查看答卷详情</span>
<span id="lblMsg">考试安排已结束</span>
<table class="mt15 exam-history-table">
<tr><th>时间</th><th>成绩</th><th>结果</th></tr>
<tr><td><span class="pl20">2026-05-22 16:19:49</span></td><td>94</td><td class="text-center">通过</td></tr>
<tr><td><span class="pl20">2026-05-22 16:02:13</span></td><td>89</td><td class="text-center">未通过</td></tr>
</table>
""")
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("""
<div class="content-body plandetailhead">
<div class="mb20 span-24 font-size-20"><span title="安全规范">安全规范</span></div>
<span id="lblCertificate">-</span>
<span id="Span1">123<span data-localize="sty_lbl_minute"></span></span>
<span id="lblTotalScore">123<span data-localize="sty_lbl_minute"></span></span>
<span id="lblPassScore">0<span data-localize="sty_lbl_minute"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<label data-localizeph="sty_lbl_ranknumber"><label><label>2846</label></label></label>
<div class="schedule1 floatleft">100%</div>
<label data-localize="mgt_lbl_requirecompletedate"></label>:2026-11-25
</div>
<div id="knowledgestudy">
<table class="table1 mt30">
<tr><th width="30"><span class="el-mixtrain-num">1</span></th><th class="text-left"><span>规范学习</span></th>
<th>:123<span data-localize="sty_lbl_minute"></span>
<span data-localize="common_lbl_totalscore"></span>:12.3</th></tr>
<tr class="hand">
<td><span class="st" title='1.1分享.mp4'>1.1分享.mp4</span></td>
<td>
<span class="fontnumber" title="已获学分">0</span>&nbsp;/&nbsp;<span class="fontnumber" title="标准学分">5.2</span>
<span data-localize="core_lbl_knghours"></span>:52&nbsp;/&nbsp;52<span data-localize="sty_lbl_minute"></span>
<span>100%</span>
</td>
</tr>
</table>
</div>
""")
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",
}