diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 6da6d54..59a6976 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -8,6 +8,7 @@ import random import re import time import uuid +from datetime import datetime from urllib.parse import quote import httpx @@ -55,6 +56,80 @@ def data_uri(value: str) -> str: return "data:image/png;base64," + value +def training_form(page: str) -> dict[str, str]: + found: dict[str, str] = {} + for match in re.finditer(r"]*>", 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"
  • ", 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'\s*([^<]+)', block) + assigned = re.search(r"sty_lbl_assignedtime\">([^<]+)", block) + credits = re.search(r"el-plan-time'>([^<]+)", 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'
  • [\s\S]*?
  • ', 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">:([^<&]+)', 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: """返回滑块左边缘在底图上的横坐标。""" 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 = 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 { "name": info.get("cnName") or "", "avatar": info.get("headPictureUrl") or "", @@ -443,9 +514,9 @@ class EunivClient: "total_score": score.get("actualStudyScore") or period.get("totalScores") or "", "today_hours": today.get("studyHours"), "today_score": today.get("studyScore"), - "pending_exam_count": pending_count, - "pending_exams": self._pending_exams(pending_count), "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: @@ -453,21 +524,50 @@ class EunivClient: match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text) return match.group(1) if match else "" + def _ensure_site(self) -> None: + if self._profile.get("token") and not getattr(self, "_site_ready", False): + probe = self.client.get( + f"{EUNIV}/study/myperiod.htm", + headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, + ) + if "spMonthlyPeriod" not in probe.text: + self.authorize(self._profile) + self._site_ready = True + def _study_period_page(self) -> str: + self._ensure_site() response = self.client.get( f"{EUNIV}/study/myperiod.htm", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"}, ) - if "spMonthlyPeriod" in response.text: - return response.text - if self._profile.get("token"): - self.authorize(self._profile) - response = self.client.get( - f"{EUNIV}/study/myperiod.htm", - headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"}, - ) 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: try: response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"") @@ -476,22 +576,22 @@ class EunivClient: payload = response.json() return isinstance(payload, dict) and bool(payload.get("cnName")) - def _pending_exams(self, count: int) -> list[dict]: - if count <= 0: - return [] - response = self._request( - "GET", - f"{EUNIV}/exam/userallexam.htm", - headers={"Accept": "text/html,application/xhtml+xml"}, - ) - names = [] - for match in response.text.split("lblExamName"): - if ">" not in match: - continue - text = match.split(">", 1)[1].split("<", 1)[0].strip() - if text: - names.append(text) - return [{"name": name, "deadline": ""} for name in names] + def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]: + items = parse(html) + seen = {(item.get("name", ""), item.get(identity, "")) for item in items} + for _ in range(10): + count = re.search(r'id="hidDatasCoun"[^>]*value="(\d+)"', html) + if not count or count.group(1) != "20": + break + form = training_form(html) + form["btnLoadNext"] = "加载更多" + html = self.client.post(url, data=form, headers=headers).text + fresh = [item for item in parse(html) if (item.get("name", ""), item.get(identity, "")) not in seen] + if not fresh: + break + items.extend(fresh) + seen.update((item.get("name", ""), item.get(identity, "")) for item in fresh) + return items def open_session(self) -> dict: profile = self.login() diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 8390a11..726dd1e 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -78,8 +78,9 @@ class FakeClient: "total_score": "3.00", "today_hours": "1", "today_score": "0.10", - "pending_exam_count": 1, - "pending_exams": [{"name": "安全考试", "deadline": ""}], + "month_hours": "60", + "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 body = home.json() 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: account = db.get(Account, "6650000146") assert account is not None @@ -260,3 +261,57 @@ def test_browser_session_logout_and_revoke() -> None: assert account is not None assert account.credential_cipher == "" assert decrypt_secret(account.password_cipher) == "secret-pass" + + +def test_parse_training_cards_keeps_status() -> None: + from euniv.client import parse_training_cards + + html = """ +
  • +
    +
    + 租赁人员数据保护合规培训-2026
    + + Jiang Mingjun 194 天 + 1 +
  • + """ + 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 = """ +
  • + 较远的考试 + + :2020-01-01 00:00:00  +
  • +
  • + 较近的考试 + + :2026-10-20 00:01:00  +
  • + """ + 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] == ["刚指派", "很久以前"] diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 5394a3e..966e1cf 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -4,7 +4,17 @@ import { NAlert, NDataTable } from "naive-ui"; interface ExamItem { name: string; - deadline: string; + status: string; + start: string; +} + +interface TrainingItem { + name: string; + status: string; + progress: number; + owner: string; + assigned: string; + credits: string; } interface HomeProfile { @@ -19,8 +29,8 @@ interface HomeProfile { total_score: string; today_hours: string | number | null; today_score: string | number | null; - pending_exam_count: number; - pending_exams: ExamItem[]; + exams: ExamItem[]; + trainings: TrainingItem[]; } const props = defineProps<{ employeeId: string }>(); @@ -44,11 +54,27 @@ const facts = computed(() => { ]; }); -const columns = [ - { title: "考试", key: "name" }, - { title: "时间", key: "deadline" }, +const examColumns = [ + { title: "名称", key: "name" }, + { 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() { const current = ++requestId; loading.value = profile.value === null; @@ -102,15 +128,14 @@ onUnmounted(() => window.clearInterval(timer));
    {{ item.value }}
    -

    待考试

    -

    {{ profile.pending_exam_count > 0 ? `有 ${profile.pending_exam_count} 场待考试` : "没有待考试" }}

    - -

    清单还没有返回考试名称。

    +

    我的考试

    + + + +

    线上培训

    + + +