feat: 首页显示全部线上培训和我的考试,并按离现在更近的时间排序
This commit is contained in:
+128
-28
@@ -8,6 +8,7 @@ import random
|
|||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -55,6 +56,80 @@ def data_uri(value: str) -> str:
|
|||||||
return "data:image/png;base64," + value
|
return "data:image/png;base64," + value
|
||||||
|
|
||||||
|
|
||||||
|
def training_form(page: str) -> dict[str, str]:
|
||||||
|
found: dict[str, str] = {}
|
||||||
|
for match in re.finditer(r"<input\b[^>]*>", page, re.I):
|
||||||
|
tag = match.group(0)
|
||||||
|
if re.search(r"""type=['"]submit['"]""", tag, re.I):
|
||||||
|
continue
|
||||||
|
name = re.search(r"""name=['"]([^'"]+)['"]""", tag)
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
value = re.search(r"""value=['"]([^'"]*)['"]""", tag)
|
||||||
|
raw = value.group(1) if value else ""
|
||||||
|
found[name.group(1)] = raw.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"')
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _by_closeness(items: list[dict], key: str) -> list[dict]:
|
||||||
|
ordered = sorted(items, key=lambda item: item.get(key, float("inf")))
|
||||||
|
for item in ordered:
|
||||||
|
item.pop(key, None)
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
progress = re.search(r'progress="(\d+)"', block)
|
||||||
|
name = re.search(r'class="font-size-16 text-color6 ellipsis">\s*([^<]+)', block)
|
||||||
|
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)
|
||||||
|
assigned_text = ""
|
||||||
|
if assigned:
|
||||||
|
assigned_text = assigned.group(1).replace(" ", " ").replace("\xa0", " ").strip()
|
||||||
|
items.append({
|
||||||
|
"name": (name.group(1).strip() if name else ""),
|
||||||
|
"status": status,
|
||||||
|
"progress": int(progress.group(1)) if progress else 0,
|
||||||
|
"owner": (owner.group(1).strip() if owner else ""),
|
||||||
|
"assigned": assigned_text,
|
||||||
|
"credits": (credits.group(1).strip() if credits else ""),
|
||||||
|
"sort_days": _leading_number(assigned_text),
|
||||||
|
})
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
start = re.search(r'sty_lbl_teststarttime"></span>:([^<&]+)', block)
|
||||||
|
start_text = start.group(1).replace(" ", " ").strip() if start else ""
|
||||||
|
items.append({
|
||||||
|
"name": (name.group(1).strip() if name else ""),
|
||||||
|
"status": (status.group(1).strip() if status else ""),
|
||||||
|
"start": start_text,
|
||||||
|
"sort_at": _clock_distance(start_text),
|
||||||
|
})
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _leading_number(value: str) -> float:
|
||||||
|
match = re.search(r"(\d+)", value)
|
||||||
|
return float(match.group(1)) if match else float("inf")
|
||||||
|
|
||||||
|
|
||||||
|
def _clock_distance(value: str) -> float:
|
||||||
|
match = re.search(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})", value)
|
||||||
|
if not match:
|
||||||
|
return float("inf")
|
||||||
|
moment = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S")
|
||||||
|
return abs((moment - datetime.now()).total_seconds())
|
||||||
|
|
||||||
|
|
||||||
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||||
"""返回滑块左边缘在底图上的横坐标。"""
|
"""返回滑块左边缘在底图上的横坐标。"""
|
||||||
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
||||||
@@ -428,10 +503,6 @@ class EunivClient:
|
|||||||
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
|
today_resp = self._request("GET", f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours")
|
||||||
today = today_resp.json()
|
today = today_resp.json()
|
||||||
|
|
||||||
exam_resp = self._request("POST", f"{YXT_API}/v1/user/getmyexamcountnew", content=b"")
|
|
||||||
exam_payload = exam_resp.json()
|
|
||||||
exam = exam_payload.get("data") or {}
|
|
||||||
pending_count = int(exam.get("preExamCount") or 0)
|
|
||||||
return {
|
return {
|
||||||
"name": info.get("cnName") or "",
|
"name": info.get("cnName") or "",
|
||||||
"avatar": info.get("headPictureUrl") or "",
|
"avatar": info.get("headPictureUrl") or "",
|
||||||
@@ -443,9 +514,9 @@ class EunivClient:
|
|||||||
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
|
"total_score": score.get("actualStudyScore") or period.get("totalScores") or "",
|
||||||
"today_hours": today.get("studyHours"),
|
"today_hours": today.get("studyHours"),
|
||||||
"today_score": today.get("studyScore"),
|
"today_score": today.get("studyScore"),
|
||||||
"pending_exam_count": pending_count,
|
|
||||||
"pending_exams": self._pending_exams(pending_count),
|
|
||||||
"month_hours": self._month_study_hours(),
|
"month_hours": self._month_study_hours(),
|
||||||
|
"trainings": _by_closeness(self.online_trainings(), "sort_days"),
|
||||||
|
"exams": _by_closeness(self.my_exams(), "sort_at"),
|
||||||
}
|
}
|
||||||
|
|
||||||
def _month_study_hours(self) -> str:
|
def _month_study_hours(self) -> str:
|
||||||
@@ -453,21 +524,50 @@ class EunivClient:
|
|||||||
match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text)
|
match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text)
|
||||||
return match.group(1) if match else ""
|
return match.group(1) if match else ""
|
||||||
|
|
||||||
def _study_period_page(self) -> str:
|
def _ensure_site(self) -> None:
|
||||||
response = self.client.get(
|
if self._profile.get("token") and not getattr(self, "_site_ready", False):
|
||||||
|
probe = self.client.get(
|
||||||
f"{EUNIV}/study/myperiod.htm",
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
|
||||||
)
|
)
|
||||||
if "spMonthlyPeriod" in response.text:
|
if "spMonthlyPeriod" not in probe.text:
|
||||||
return response.text
|
|
||||||
if self._profile.get("token"):
|
|
||||||
self.authorize(self._profile)
|
self.authorize(self._profile)
|
||||||
|
self._site_ready = True
|
||||||
|
|
||||||
|
def _study_period_page(self) -> str:
|
||||||
|
self._ensure_site()
|
||||||
response = self.client.get(
|
response = self.client.get(
|
||||||
f"{EUNIV}/study/myperiod.htm",
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
||||||
)
|
)
|
||||||
return response.text
|
return response.text
|
||||||
|
|
||||||
|
def online_trainings(self) -> list[dict]:
|
||||||
|
self._ensure_site()
|
||||||
|
url = f"{EUNIV}/sty/mystudytask.htm"
|
||||||
|
headers = {"User-Agent": USER_AGENT, "Referer": url, "Origin": EUNIV}
|
||||||
|
html = self.client.get(url, headers=headers).text
|
||||||
|
items = parse_training_cards(html, "进行中")
|
||||||
|
form = training_form(html)
|
||||||
|
for event, status in (("2,已完成", "已完成"), ("1,已归档", "已归档")):
|
||||||
|
form["__EVENTTARGET"] = "scType"
|
||||||
|
form["__EVENTARGUMENT"] = event
|
||||||
|
html = self.client.post(url, data=form, headers=headers).text
|
||||||
|
items.extend(parse_training_cards(html, status))
|
||||||
|
form = training_form(html)
|
||||||
|
return items
|
||||||
|
|
||||||
|
def my_exams(self) -> list[dict]:
|
||||||
|
self._ensure_site()
|
||||||
|
url = f"{EUNIV}/exam/userallexam.htm"
|
||||||
|
headers = {"User-Agent": USER_AGENT, "Referer": url, "Origin": EUNIV}
|
||||||
|
html = self.client.get(url, headers=headers).text
|
||||||
|
form = training_form(html)
|
||||||
|
form["__EVENTTARGET"] = "scExamState"
|
||||||
|
form["__EVENTARGUMENT"] = ""
|
||||||
|
html = self.client.post(url, data=form, headers=headers).text
|
||||||
|
return self._pages(url, headers, html, parse_exam_cards, "start")
|
||||||
|
|
||||||
def credential_alive(self) -> bool:
|
def credential_alive(self) -> bool:
|
||||||
try:
|
try:
|
||||||
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
||||||
@@ -476,22 +576,22 @@ class EunivClient:
|
|||||||
payload = response.json()
|
payload = response.json()
|
||||||
return isinstance(payload, dict) and bool(payload.get("cnName"))
|
return isinstance(payload, dict) and bool(payload.get("cnName"))
|
||||||
|
|
||||||
def _pending_exams(self, count: int) -> list[dict]:
|
def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]:
|
||||||
if count <= 0:
|
items = parse(html)
|
||||||
return []
|
seen = {(item.get("name", ""), item.get(identity, "")) for item in items}
|
||||||
response = self._request(
|
for _ in range(10):
|
||||||
"GET",
|
count = re.search(r'id="hidDatasCoun"[^>]*value="(\d+)"', html)
|
||||||
f"{EUNIV}/exam/userallexam.htm",
|
if not count or count.group(1) != "20":
|
||||||
headers={"Accept": "text/html,application/xhtml+xml"},
|
break
|
||||||
)
|
form = training_form(html)
|
||||||
names = []
|
form["btnLoadNext"] = "加载更多"
|
||||||
for match in response.text.split("lblExamName"):
|
html = self.client.post(url, data=form, headers=headers).text
|
||||||
if ">" not in match:
|
fresh = [item for item in parse(html) if (item.get("name", ""), item.get(identity, "")) not in seen]
|
||||||
continue
|
if not fresh:
|
||||||
text = match.split(">", 1)[1].split("<", 1)[0].strip()
|
break
|
||||||
if text:
|
items.extend(fresh)
|
||||||
names.append(text)
|
seen.update((item.get("name", ""), item.get(identity, "")) for item in fresh)
|
||||||
return [{"name": name, "deadline": ""} for name in names]
|
return items
|
||||||
|
|
||||||
def open_session(self) -> dict:
|
def open_session(self) -> dict:
|
||||||
profile = self.login()
|
profile = self.login()
|
||||||
|
|||||||
@@ -78,8 +78,9 @@ class FakeClient:
|
|||||||
"total_score": "3.00",
|
"total_score": "3.00",
|
||||||
"today_hours": "1",
|
"today_hours": "1",
|
||||||
"today_score": "0.10",
|
"today_score": "0.10",
|
||||||
"pending_exam_count": 1,
|
"month_hours": "60",
|
||||||
"pending_exams": [{"name": "安全考试", "deadline": ""}],
|
"exams": [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}],
|
||||||
|
"trainings": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -116,7 +117,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
|||||||
assert home.status_code == 200
|
assert home.status_code == 200
|
||||||
body = home.json()
|
body = home.json()
|
||||||
assert body["name"] == "测试用户"
|
assert body["name"] == "测试用户"
|
||||||
assert body["pending_exams"] == [{"name": "安全考试", "deadline": ""}]
|
assert body["exams"] == [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}]
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
account = db.get(Account, "6650000146")
|
account = db.get(Account, "6650000146")
|
||||||
assert account is not None
|
assert account is not None
|
||||||
@@ -260,3 +261,57 @@ def test_browser_session_logout_and_revoke() -> None:
|
|||||||
assert account is not None
|
assert account is not None
|
||||||
assert account.credential_cipher == ""
|
assert account.credential_cipher == ""
|
||||||
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||||
|
|
||||||
|
|
||||||
|
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")'>
|
||||||
|
<div class="el-plan-circle-progress p5" progress="100" id="demo1"></div>
|
||||||
|
<div class="font-size-16 text-color6 ellipsis">
|
||||||
|
租赁人员数据保护合规培训-2026</div>
|
||||||
|
<span class="mr10">
|
||||||
|
Jiang Mingjun</span><span data-localizeph="sty_lbl_assignedtime"><span> 194 天</span></span>
|
||||||
|
<span data-localizeph='sty_lbl_getcredits' class='el-plan-time'><span>1</span></span>
|
||||||
|
</li>
|
||||||
|
"""
|
||||||
|
rows = parse_training_cards(html, "已完成")
|
||||||
|
assert rows == [{
|
||||||
|
"name": "租赁人员数据保护合规培训-2026",
|
||||||
|
"status": "已完成",
|
||||||
|
"progress": 100,
|
||||||
|
"owner": "Jiang Mingjun",
|
||||||
|
"assigned": "194 天",
|
||||||
|
"credits": "1",
|
||||||
|
"sort_days": 194.0,
|
||||||
|
}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lists_put_the_nearest_time_first() -> None:
|
||||||
|
from euniv.client import _by_closeness, parse_exam_cards
|
||||||
|
|
||||||
|
html = """
|
||||||
|
<li name="userExam">
|
||||||
|
<a class="my-exam-title ellipsis">较远的考试</a>
|
||||||
|
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已完成" />
|
||||||
|
<span data-localize="sty_lbl_teststarttime"></span>:2020-01-01 00:00:00
|
||||||
|
</li>
|
||||||
|
<li name="userExam">
|
||||||
|
<a class="my-exam-title ellipsis">较近的考试</a>
|
||||||
|
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已过期" />
|
||||||
|
<span data-localize="sty_lbl_teststarttime"></span>:2026-10-20 00:01:00
|
||||||
|
</li>
|
||||||
|
"""
|
||||||
|
rows = _by_closeness(parse_exam_cards(html), "sort_at")
|
||||||
|
assert [item["name"] for item in rows] == ["较近的考试", "较远的考试"]
|
||||||
|
assert rows[0]["status"] == "已过期"
|
||||||
|
assert "sort_at" not in rows[0]
|
||||||
|
trainings = _by_closeness(
|
||||||
|
[
|
||||||
|
{"name": "很久以前", "sort_days": 741.0},
|
||||||
|
{"name": "刚指派", "sort_days": 5.0},
|
||||||
|
],
|
||||||
|
"sort_days",
|
||||||
|
)
|
||||||
|
assert [item["name"] for item in trainings] == ["刚指派", "很久以前"]
|
||||||
|
|||||||
@@ -4,7 +4,17 @@ import { NAlert, NDataTable } from "naive-ui";
|
|||||||
|
|
||||||
interface ExamItem {
|
interface ExamItem {
|
||||||
name: string;
|
name: string;
|
||||||
deadline: string;
|
status: string;
|
||||||
|
start: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TrainingItem {
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
progress: number;
|
||||||
|
owner: string;
|
||||||
|
assigned: string;
|
||||||
|
credits: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface HomeProfile {
|
interface HomeProfile {
|
||||||
@@ -19,8 +29,8 @@ interface HomeProfile {
|
|||||||
total_score: string;
|
total_score: string;
|
||||||
today_hours: string | number | null;
|
today_hours: string | number | null;
|
||||||
today_score: string | number | null;
|
today_score: string | number | null;
|
||||||
pending_exam_count: number;
|
exams: ExamItem[];
|
||||||
pending_exams: ExamItem[];
|
trainings: TrainingItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = defineProps<{ employeeId: string }>();
|
const props = defineProps<{ employeeId: string }>();
|
||||||
@@ -44,11 +54,27 @@ const facts = computed(() => {
|
|||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
const columns = [
|
const examColumns = [
|
||||||
{ title: "考试", key: "name" },
|
{ title: "名称", key: "name" },
|
||||||
{ title: "时间", key: "deadline" },
|
{ title: "状态", key: "status" },
|
||||||
|
{ title: "开始", key: "start" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const trainingColumns = [
|
||||||
|
{ title: "名称", key: "name" },
|
||||||
|
{ title: "状态", key: "status" },
|
||||||
|
{ title: "进度", key: "progressText" },
|
||||||
|
{ title: "学分", key: "credits" },
|
||||||
|
{ title: "指派", key: "assigned" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const trainingRows = computed(() =>
|
||||||
|
(profile.value?.trainings || []).map((item) => ({
|
||||||
|
...item,
|
||||||
|
progressText: `${item.progress}%`,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
const current = ++requestId;
|
const current = ++requestId;
|
||||||
loading.value = profile.value === null;
|
loading.value = profile.value === null;
|
||||||
@@ -102,15 +128,14 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
<dd>{{ item.value }}</dd>
|
<dd>{{ item.value }}</dd>
|
||||||
</div>
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
<h3>待考试</h3>
|
<h3>我的考试</h3>
|
||||||
<p class="home-status">{{ profile.pending_exam_count > 0 ? `有 ${profile.pending_exam_count} 场待考试` : "没有待考试" }}</p>
|
<n-data-table :columns="examColumns" :data="profile.exams || []" :bordered="false">
|
||||||
<n-data-table
|
<template #empty>没有考试</template>
|
||||||
v-if="profile.pending_exams.length"
|
</n-data-table>
|
||||||
:columns="columns"
|
<h3>线上培训</h3>
|
||||||
:data="profile.pending_exams"
|
<n-data-table :columns="trainingColumns" :data="trainingRows" :bordered="false">
|
||||||
:bordered="false"
|
<template #empty>没有线上培训</template>
|
||||||
/>
|
</n-data-table>
|
||||||
<p v-else-if="profile.pending_exam_count > 0" class="home-status">清单还没有返回考试名称。</p>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
Reference in New Issue
Block a user