feat: 历史统计时对照显示官方本月学时

This commit is contained in:
Nixevol
2026-11-19 02:54:32 +08:00
parent ba787a513b
commit a0ceb51348
12 changed files with 156 additions and 13 deletions
+22 -4
View File
@@ -62,8 +62,10 @@ def _iso_time(value: datetime | None) -> str | None:
def list_users(db: Session) -> list[dict]:
from admin.settings import hours_source_of
from euniv.autostudy import autostudy_status, work_running
source = hours_source_of()
accounts = db.scalars(select(Account).order_by(Account.employee_id)).all()
live_users = autostudy_status().get("users") or {}
rows = []
@@ -82,6 +84,8 @@ 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 "",
"official_month_hours": account.official_month_hours or "",
"hours_source": source,
"monthly_target": account.monthly_target if account.monthly_target is not None else 600,
"has_proxy": enabled(account),
"proxy": summary_of(account),
@@ -111,13 +115,23 @@ def _require(db: Session, employee_id: str) -> Account:
return account
def _checked_hours(client) -> str:
def _checked_hours(client) -> tuple[str, str]:
from admin.settings import hours_source_of
from euniv.service import _month_hours
try:
return _month_hours(client)
hours = _month_hours(client)
except Exception:
return ""
hours = ""
official = ""
if hours and hours_source_of() == "history":
reader = getattr(client, "month_hours", None)
if callable(reader):
try:
official = str(reader() or "").strip()
except Exception:
official = ""
return hours, official
def _checked_profile(client) -> dict:
@@ -146,6 +160,7 @@ def check_employee(db: Session, employee_id: str) -> dict:
valid: bool | None = None
profile: dict = {}
hours = ""
official_hours = ""
try:
for _ in range(MAX_SWITCHES + 1):
proxy = bind_url(account) if pooled else url_of(account)
@@ -157,11 +172,12 @@ def check_employee(db: Session, employee_id: str) -> dict:
valid = alive
profile = _checked_profile(client) if alive else {}
if alive:
hours = _checked_hours(client)
hours, official_hours = _checked_hours(client)
break
except Exception as exc:
profile = {}
hours = ""
official_hours = ""
if pooled and proxy and is_proxy_failure(exc):
retire_if_dead(employee_id, proxy, str(exc)[:200])
client.close()
@@ -190,6 +206,8 @@ def check_employee(db: Session, employee_id: str) -> dict:
from euniv.study_control import stamp_hours
stamp_hours(account, hours)
if official_hours:
account.official_month_hours = official_hours[:32]
db.commit()
payload = {"employee_id": employee_id, "result": result}
if result == "检查失败":
@@ -0,0 +1,19 @@
"""记下页面上的本月学时,便于和系统统计对照。"""
from alembic import op
import sqlalchemy as sa
revision = "0014_official_month_hours"
down_revision = "0013_study_opened_at"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.add_column(sa.Column("official_month_hours", sa.String(length=32), server_default="", nullable=False))
def downgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.drop_column("official_month_hours")
+10 -2
View File
@@ -892,16 +892,22 @@ class HoursWatcher:
from admin.settings import hours_source_of
source = hours_source_of()
official = ""
if source == "history":
current = int(await self.session.month_history_minutes())
text = str(current)
try:
official = await self.session.month_hours_text()
except Exception:
official = ""
else:
text = await self.session.month_hours_text()
current = _parse_minutes(text)
official = text
if not text:
raise RuntimeError("学时没有解析到")
self._misses = 0
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
await asyncio.to_thread(_update_month_hours, self.employee_id, text, official)
target = self.current_target()
if target > 0 and current >= target:
self.reached = True
@@ -2389,12 +2395,14 @@ class AutoStudyWorker:
# ── 数据库更新 ──
def _update_month_hours(employee_id: str, hours: str) -> None:
def _update_month_hours(employee_id: str, hours: str, official: str = "") -> None:
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account:
stamp_hours(account, hours)
if official.strip():
account.official_month_hours = official.strip()[:32]
db.commit()
_set_user_status(employee_id, month_hours=hours)
+1
View File
@@ -56,6 +56,7 @@ class Account(Base):
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default=text("''"))
official_month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default=text("''"))
user_name: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default=text("''"))
company: Mapped[str] = mapped_column(String(300), nullable=False, default="", server_default=text("''"))
hours_month: Mapped[str] = mapped_column(String(7), nullable=False, default="", server_default=text("''"))
+8
View File
@@ -416,6 +416,7 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic
data = dict(summary)
source = hours_source_of()
data["hours_source"] = source
data["official_month_hours"] = data.get("month_hours")
if source != "history":
return data
walker = getattr(client, "month_history_minutes", None)
@@ -440,6 +441,7 @@ def _api_hour_fields(client) -> dict:
return {
"year_hours": summary.get("year_hours"),
"month_hours": summary.get("month_hours"),
"official_month_hours": summary.get("official_month_hours") or summary.get("month_hours"),
"today_hours": summary.get("today_hours"),
"total_hours": summary.get("total_hours"),
}
@@ -461,6 +463,11 @@ def _remember_month_hours(db: Session, employee_id: str, payload: dict) -> None:
from euniv.study_control import stamp_hours
stamp_hours(account, text)
official = payload.get("official_month_hours")
if official is not None and not isinstance(official, bool):
official_text = str(official).strip()
if official_text:
account.official_month_hours = official_text[:32]
db.commit()
@@ -497,6 +504,7 @@ def _hour_fields(data: dict) -> dict:
"hours_source": data.get("hours_source") or "api",
"year_hours": data.get("year_hours"),
"month_hours": data.get("month_hours"),
"official_month_hours": data.get("official_month_hours"),
"today_hours": data.get("today_hours"),
"total_hours": data.get("total_hours"),
}
+2
View File
@@ -508,6 +508,8 @@ def test_check_skips_empty_credential_and_updates_saved_one(monkeypatch) -> None
"last_refresh_at",
"credential_valid",
"month_hours",
"official_month_hours",
"hours_source",
"monthly_target",
"has_proxy",
"proxy",
+2
View File
@@ -150,6 +150,7 @@ def test_login_stores_password_and_credential_only(monkeypatch) -> None:
"last_refresh_at",
"credential_valid",
"month_hours",
"official_month_hours",
"user_name",
"company",
"hours_month",
@@ -1155,6 +1156,7 @@ def test_home_and_history_hours_follow_source(monkeypatch) -> None:
history = client.get("/api/home/history")
assert home.json()["hours_source"] == history.json()["hours_source"] == "history"
assert home.json()["month_hours"] == history.json()["month_hours"] == 2
assert home.json()["official_month_hours"] == history.json()["official_month_hours"] == "60"
assert home.json()["year_hours"] == history.json()["year_hours"] == "100"
assert home.json()["total_hours"] == history.json()["total_hours"] == "10"
assert home.json()["today_hours"] == history.json()["today_hours"] == 1
+13 -1
View File
@@ -3,6 +3,7 @@ import { apiFetch } from "../../shared/http";
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInputNumber, NModal, NRadioButton, NRadioGroup, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, RefreshOutline, SettingsOutline } from "@vicons/ionicons5";
import HoursCompare from "../../shared/HoursCompare.vue";
import ProxyFields from "../../shared/ProxyFields.vue";
import { ADMIN_DAY_MAX, ADMIN_DAY_MIN, STUDY_DAY_DEFAULT, adminDayOptions, workerOptions } from "../../shared/studyFields";
import { isRecord, textOf } from "../../shared/text";
@@ -16,6 +17,8 @@ interface UserRow {
last_refresh_at: string | null;
credential_valid: boolean | null;
month_hours: string;
official_month_hours: string;
hours_source: "api" | "history";
monthly_target: number;
has_proxy: boolean;
proxy: string;
@@ -174,6 +177,8 @@ 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),
official_month_hours: textOf(value.official_month_hours),
hours_source: value.hours_source === "history" ? "history" : "api",
monthly_target: typeof value.monthly_target === "number" ? value.monthly_target : 600,
has_proxy: value.has_proxy === true,
proxy: textOf(value.proxy),
@@ -919,7 +924,14 @@ onMounted(() => {
<td class="name">{{ row.user_name || "—" }}</td>
<td class="company">{{ row.company || "—" }}</td>
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
<td class="when">{{ monthHoursText(row) }}</td>
<td class="when">
{{ monthHoursText(row) }}
<HoursCompare
v-if="row.hours_source === 'history' && monthHoursText(row) !== '—'"
:system="row.month_hours"
:official="row.official_month_hours"
/>
</td>
<td :class="taskText(row) === '运行中' ? 'ok' : 'quiet'">{{ taskText(row) }}</td>
<td class="when">{{ formatRefreshTime(row.study_opened_at) || "—" }}</td>
<td class="when">{{ row.proxy || "—" }}</td>
+17 -3
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import HoursCompare from "../../shared/HoursCompare.vue";
import { computed, h, onMounted, ref } from "vue";
import { NAlert, NButton, NDataTable, NIcon, NPagination, NTooltip, type DataTableColumns } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -16,6 +17,8 @@ interface HistoryHours {
month_hours: string | number | null;
today_hours: string | number | null;
total_hours: string | number | null;
hours_source: "api" | "history";
official_month_hours: string;
}
type SectionState = "loading" | "ready" | "error";
@@ -95,6 +98,10 @@ async function load() {
month_hours: asHour(payload.month_hours),
today_hours: asHour(payload.today_hours),
total_hours: asHour(payload.total_hours),
hours_source: payload.hours_source === "history" ? "history" : "api",
official_month_hours: typeof payload.official_month_hours === "string" || typeof payload.official_month_hours === "number"
? String(payload.official_month_hours)
: "",
};
historyLimited.value = payload.limited === true;
errorText.value = "";
@@ -119,12 +126,12 @@ function refresh() {
});
}
const historyFacts = computed(() => {
const historyFacts = computed<Array<{ label: string; value: string; compare?: boolean }>>(() => {
const current = hours.value;
return [
{ label: "总学时", value: current ? withMinutes(amount(current.total_hours)) : "" },
{ label: "本年学时", value: current ? withMinutes(amount(current.year_hours)) : "" },
{ label: "本月学时", value: current ? withMinutes(amount(current.month_hours)) : "" },
{ label: "本月学时", value: current ? withMinutes(amount(current.month_hours)) : "", compare: current?.hours_source === "history" },
{ label: "本日学时", value: current ? withMinutes(amount(current.today_hours)) : "" },
];
});
@@ -226,7 +233,14 @@ onMounted(refresh);
<dt>{{ item.label }}</dt>
<dd>
<span v-if="state === 'loading'" class="bone bone-value"></span>
<template v-else>{{ state === "ready" ? item.value : "—" }}</template>
<template v-else>
{{ state === "ready" ? item.value : "—" }}
<HoursCompare
v-if="state === 'ready' && item.compare && item.value && item.value !== '—'"
:system="String(hours?.month_hours ?? '')"
:official="hours?.official_month_hours ?? ''"
/>
</template>
</dd>
</div>
</dl>
+23 -3
View File
@@ -3,6 +3,7 @@ import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInputNumber, NModal, NProgress, NRadioButton, NRadioGroup, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
import HoursCompare from "../../shared/HoursCompare.vue";
import ProxyFields from "../../shared/ProxyFields.vue";
import { STUDY_DAY_DEFAULT, STUDY_DAY_MAX, STUDY_DAY_MIN, dayOptions, workerOptions } from "../../shared/studyFields";
import { failureText } from "../../shared/text";
@@ -19,6 +20,7 @@ interface HomeSummary {
total_score: string;
points: string | number | null;
hours_source: "api" | "history";
official_month_hours: string;
limited?: boolean;
}
@@ -161,11 +163,25 @@ function withMinutes(value: string) {
const historyHoursNote = "由于Euniv学时统计缺陷/统计延后,本系统已开启采用当月学习历史统计本月学时,可能会导致本系统中显示的本月学时与Euniv官方网站不一样。";
const facts = computed(() => {
interface HourFact {
label: string;
value: string;
compare?: boolean;
system?: string;
official?: string;
}
const facts = computed<HourFact[]>(() => {
const current = summary.value;
return [
{ label: "本年学时", value: current ? withMinutes(amount(current.year_hours)) : "" },
{ label: "本月学时", value: current ? withMinutes(amount(current.month_hours)) : "" },
{
label: "本月学时",
value: current ? withMinutes(amount(current.month_hours)) : "",
compare: current?.hours_source === "history",
system: current?.month_hours ?? "",
official: current?.official_month_hours ?? "",
},
{ label: "本日学时", value: current ? withMinutes(amount(current.today_hours)) : "" },
{ label: "总学时", value: current ? withMinutes(amount(current.total_hours)) : "" },
{ label: "累计学分", value: current ? amount(current.total_score) : "" },
@@ -186,6 +202,7 @@ function asSummary(value: unknown): HomeSummary | null {
level: typeof row.level === "string" ? row.level : "",
year_hours: String(text("year_hours") ?? ""),
month_hours: String(text("month_hours") ?? ""),
official_month_hours: String(text("official_month_hours") ?? ""),
today_hours: typeof row.today_hours === "number" || typeof row.today_hours === "string" ? row.today_hours : null,
total_hours: String(text("total_hours") ?? ""),
total_score: String(text("total_score") ?? ""),
@@ -1017,7 +1034,10 @@ onUnmounted(() => {
<dt>{{ item.label }}</dt>
<dd>
<span v-if="summaryState === 'loading'" class="bone bone-value"></span>
<template v-else>{{ item.value || "—" }}</template>
<template v-else>
{{ item.value || "—" }}
<HoursCompare v-if="item.compare && item.value && item.value !== '—'" :system="String(item.system || '')" :official="String(item.official || '')" />
</template>
</dd>
</div>
</dl>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { NTooltip } from "naive-ui";
defineProps<{
system: string;
official: string;
}>();
function minutes(value: string) {
const text = value.trim();
return text ? `${text} 分钟` : "—";
}
</script>
<template>
<n-tooltip placement="top">
<template #trigger>
<sup class="hours-mark" tabindex="0">对比</sup>
</template>
<div class="hours-compare">
<div>系统统计: {{ minutes(system) }}</div>
<div>官方统计: {{ minutes(official) }}</div>
</div>
</n-tooltip>
</template>
+14
View File
@@ -1019,6 +1019,20 @@ select {
font-variant-numeric: tabular-nums;
}
.hours-mark {
margin-left: 4px;
color: #f5a524;
font-size: 11px;
font-weight: 650;
letter-spacing: 0;
cursor: help;
vertical-align: super;
}
.hours-compare {
line-height: 1.6;
}
.board {
min-width: 0;
min-height: 0;