feat: 登录后进入实时首页,并加密保存可刷新的登录凭证

This commit is contained in:
2026-10-26 18:12:00 +08:00
parent eaad01d5a8
commit 91707f959f
14 changed files with 748 additions and 136 deletions
+57 -9
View File
@@ -1,17 +1,65 @@
---
name: EunivTools
description: 石墨工作台。网页自己顶着产品名,版面是居中登录卡和左侧导航。
colors:
ground: "#0D1117"
panel: "#161A22"
elevated: "#1B212B"
text: "#E6EDF3"
muted: "#9AA4AE"
line: "#262C36"
accent: "#79C0FF"
primary: "#1F6FEB"
primary-hover: "#388BFD"
danger: "#F85149"
day-ground: "#F6F8FA"
day-panel: "#FFFFFF"
day-text: "#0D1117"
day-muted: "#57606A"
day-line: "#D0D7DE"
day-accent: "#0969DA"
typography:
body:
fontFamily: "Segoe UI, Microsoft YaHei, sans-serif"
fontSize: "14px"
fontWeight: 400
lineHeight: 1.5
letterSpacing: "normal"
title:
fontFamily: "Segoe UI, Microsoft YaHei, sans-serif"
fontSize: "22px"
fontWeight: 650
lineHeight: 1.3
letterSpacing: "-0.03em"
rounded:
sm: "4px"
spacing:
sm: "8px"
md: "16px"
lg: "28px"
components:
button-primary:
backgroundColor: "{colors.primary}"
textColor: "#FFFFFF"
rounded: "{rounded.sm}"
padding: "8px 16px"
button-destructive:
backgroundColor: "transparent"
textColor: "{colors.danger}"
rounded: "{rounded.sm}"
padding: "8px 12px"
---
# Design
视觉方案由 `web/src/shared/theme.ts` 里的方案对象生成。每套方案提供日夜标记、主色,以及 `--bg`、`--panel`、`--ink`、`--muted`、`--line`、`--accent`、`--accent-soft`、`--sidebar`。切换方案时写入 `documentElement` 的 CSS 变量,并同步 Naive UI 的主色。
登录页和侧栏不写死颜色。它们使用这些变量和 Naive UI 组件。
视觉方案在 `web/src/shared/theme.ts`。`graphite` 是默认,`day` 是同一套缝和按钮的日间。颜色写进 CSS 变量,Naive UI 的主色、面板和菜单跟着变。
## 结构
- 未登录:全屏 `--bg`,居中 `--panel` 登录卡,标签在左、控件在右,右上角切换日夜。
- 已登录:左侧 220px 可折叠导航,底部是工号、主题和退出。右侧是当前页。
未登录时,画面中央是一张登录卡,右上角切换日夜。登录后,左侧 220px 可折叠导航:顶部是线框 E 和 EunivTools,中间是菜单,底部是工号、主题和退出。退出在主题切换右边。
## 现有方案
这是网页,侧栏必须自己放图标和标题。版面参考居中登录卡和左导航,不照搬其它产品的功能页。
- `light`:白底、`#111827` 正文、`#2563eb` 主色。
- `dark`:同一结构的深色。
## 签名
新增视觉方案时,只在 `schemes` 里增加一项,不改登录页和侧栏组件。
选中的菜单项只有一条强调色左边线,没有色块。退出是主题切换右边的红色图标。
+8 -8
View File
@@ -8,7 +8,7 @@ web
## Stack
Vue 3、TypeScript、Vite、Naive UI。后端 FastAPI,数据 SQLite。视觉方案按 NqiTools 的方式生成:一组可替换的方案令牌,登录页和侧边导航共用同一套结构。
Vue 3、TypeScript、Vite、Naive UI。后端 FastAPI,数据 SQLite。视觉用可替换的方案令牌,登录页和侧栏共用这些令牌。
## Users
@@ -24,25 +24,25 @@ Vue 3、TypeScript、Vite、Naive UI。后端 FastAPI,数据 SQLite。视觉
## Operating Context
使用者打开网页,先看到登录页,登录后进入带左侧导航的工作台。日间和夜间可以切换。以后可以换成另一套视觉方案,而不改登录页和侧栏的结构。
使用者打开网页,先看到登录页,登录后进入带左侧导航的工作台。侧栏顶部有产品图标和名称。日间和夜间可以切换。
## Capabilities and Constraints
- 登录页收集工号和密码,提交后调用 `/api/login`。
- 成功后进入侧栏工作台。当前页面只列出已保存的工号。
- 成功后进入首页。头像、姓名、学时、学分和待考试每次现查,不写入本地。登录凭证加密保存,刷新后更新。
- 本地数据库只存工号和加密密码。
- 界面结构对齐 NqiTools:居中登录卡、左侧可折叠导航、底部账号与主题切换。
- 网页视觉以后再细调时,替换方案令牌,不重做登录页和侧栏骨架。
- 版面借用居中登录卡和左侧可折叠导航。侧栏顶部保留图标和 EunivTools,因为这是网页,没有桌面窗口标题栏。
- 不照搬 NqiTools 的页面。那个产品是 Tauri 客户端,功能与这里不同。
## Brand Commitments
产品名是 EunivTools。登录页和侧边导航采用 NqiTools 已确认的结构:白底、蓝色主按钮、左导航、日间与夜间切换。不使用运营商标志。
产品名是 EunivTools。当前视觉是石墨工作台:深色底板、细缝、蓝色主按钮。退出在主题切换右边。同一套结构可以切到日间。不使用运营商标志。
## Evidence on Hand
- 登录接口:`POST /api/login`,成功时返回 `{ employee_id }`。
- 使用者列表:`GET /api/accounts`,每项只有 `employee_id`。
- 参考实现:`E:/code/NqiTools/desktop/src` 的登录页、侧栏和主题切换。
- 首页:`GET /api/home?employee_id=`,返回现查的个人信息和待考试,不写入数据库。
- 版面参考:`E:/code/NqiTools/desktop/src` 的居中登录卡和左侧导航,只参考版面,不参考它的功能页。
## Product Principles
@@ -0,0 +1,19 @@
"""保存加密后的登录凭证。"""
from alembic import op
import sqlalchemy as sa
revision = "0003_credentials"
down_revision = "0002_accounts_only"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.add_column(sa.Column("credential_cipher", sa.Text(), nullable=False, server_default=""))
def downgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.drop_column("credential_cipher")
+8 -5
View File
@@ -1,4 +1,4 @@
"""登录接口。本地只保存工号和加密密码。"""
"""登录接口。本地保存工号、加密密码和加密后的登录凭证。"""
from __future__ import annotations
@@ -11,7 +11,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from euniv.db import get_db, init_db
from euniv.service import list_accounts, login_and_store
from euniv.service import fetch_home, login_and_store
@asynccontextmanager
@@ -43,9 +43,12 @@ def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
return {"employee_id": employee_id}
@app.get("/api/accounts")
def accounts(db: Session = Depends(get_db)) -> list[dict]:
return [{"employee_id": item.employee_id} for item in list_accounts(db)]
@app.get("/api/home")
def home(employee_id: str, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home(db, employee_id.strip())
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
+121
View File
@@ -76,11 +76,17 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
return best_x
class SessionExpired(RuntimeError):
"""学习平台凭证失效,需要重新登录。"""
class EunivClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name.strip()
self.password = password
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
self._profile: dict = {}
self._yxt_token = ""
def close(self) -> None:
self.client.close()
@@ -220,14 +226,72 @@ class EunivClient:
if code != "0000" or not isinstance(redirect_url, str):
raise RuntimeError(f"申请学习平台授权码失败:{message}")
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
self._profile = {
"token": str(profile.get("token") or ""),
"accountId": account_id,
"userId": user_id,
"ssoinfo": str(profile.get("ssoinfo") or ""),
"unionId": str(profile.get("unionId") or ""),
}
self._yxt_token = ""
self.session_token()
def export_credential(self) -> dict:
profile = self._profile
return {
"ucs_token": str(profile.get("token") or ""),
"ucs_account_id": str(profile.get("accountId") or ""),
"ucs_user_id": str(profile.get("userId") or ""),
"ucs_ssoinfo": str(profile.get("ssoinfo") or ""),
"ucs_union_id": str(profile.get("unionId") or ""),
"yxt_token": self.session_token(),
}
def restore(self, credential: dict) -> None:
self._profile = {
"token": str(credential.get("ucs_token") or ""),
"accountId": str(credential.get("ucs_account_id") or ""),
"userId": str(credential.get("ucs_user_id") or ""),
"ssoinfo": str(credential.get("ucs_ssoinfo") or ""),
"unionId": str(credential.get("ucs_union_id") or ""),
}
token = str(credential.get("yxt_token") or "")
self._yxt_token = token
if token:
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/")
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/")
def session_token(self) -> str:
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
self._yxt_token = cookie.value
return cookie.value
if self._yxt_token:
return self._yxt_token
names = sorted({cookie.name for cookie in self.client.cookies.jar})
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
def _request(self, method: str, url: str, **kwargs) -> httpx.Response:
headers = self.api_headers()
extra = kwargs.pop("headers", None)
if extra:
headers.update(extra)
response = self.client.request(method, url, headers=headers, **kwargs)
refreshed = response.headers.get("token") or response.headers.get("Token")
if refreshed:
self._yxt_token = refreshed
self.client.cookies.set("ELEARNING_00024", refreshed, domain="euniv.zte.com.cn", path="/")
for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value:
self._yxt_token = cookie.value
if response.status_code in (401, 403):
raise SessionExpired("学习平台登录已失效")
if response.headers.get("content-type", "").startswith("application/json"):
payload = response.json()
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
raise SessionExpired("学习平台登录已失效")
return response
def user_info(self) -> dict:
response = self.client.post(
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
@@ -292,6 +356,63 @@ class EunivClient:
"class_count": class_count,
}
def home_snapshot(self) -> dict:
"""实时读取首页要展示的个人信息,调用方不得把结果写入数据库。"""
info_resp = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
info = info_resp.json()
if not isinstance(info, dict) or "cnName" not in info:
raise RuntimeError("用户信息返回无法识别")
period_resp = self._request("GET", f"{STUDY_API}/v1/frw/user/info")
period = period_resp.json()
if not isinstance(period, dict) or "yearScores" not in period:
raise RuntimeError("本年和本月学分返回无法识别")
score_resp = self._request("POST", f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour", json={})
score_payload = score_resp.json()
score = score_payload.get("data") or {}
if score_payload.get("code") not in (None, "0", 0):
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
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 "",
"department": info.get("departmentName") or "",
"level": period.get("levelName") or info.get("userClassLevelName") or "",
"year_score": period.get("yearScores") or "0.00",
"month_score": period.get("monthScores") or "0.00",
"total_hours": score.get("actualStudyHour") or "",
"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),
}
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 open_session(self) -> dict:
profile = self.login()
self.authorize(profile)
+2 -1
View File
@@ -1,4 +1,4 @@
"""本地只保存工号和加密后的密码。"""
"""本地保存工号、加密密码和加密后的登录凭证。"""
from __future__ import annotations
@@ -15,3 +15,4 @@ class Account(Base):
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
password_cipher: Mapped[str] = mapped_column(Text)
credential_cipher: Mapped[str] = mapped_column(Text, default="")
+38 -9
View File
@@ -1,34 +1,63 @@
"""校验 e 学登录,并只把工号和加密密码写入本地库。"""
"""校验 e 学登录。本地只保存工号、加密密码和加密后的登录凭证。"""
from __future__ import annotations
from sqlalchemy import select
import json
from sqlalchemy.orm import Session
from euniv.client import EunivClient
from euniv.client import EunivClient, SessionExpired
from euniv.crypto import decrypt_secret, encrypt_secret
from euniv.models import Account
def _dump(credential: dict) -> str:
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
client = client_factory(employee_id, password)
try:
client.login()
profile = client.login()
client.authorize(profile)
credential = client.export_credential()
finally:
client.close()
account = db.get(Account, employee_id)
if account is None:
account = Account(employee_id=employee_id, password_cipher=encrypt_secret(password))
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
db.add(account)
else:
account.password_cipher = encrypt_secret(password)
account.password_cipher = encrypt_secret(password)
account.credential_cipher = encrypt_secret(_dump(credential))
db.commit()
db.refresh(account)
return account
def list_accounts(db: Session) -> list[Account]:
return list(db.scalars(select(Account).order_by(Account.employee_id)))
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
account = db.get(Account, employee_id)
if account is None:
raise RuntimeError("请先登录")
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
client = client_factory(employee_id, decrypt_secret(account.password_cipher))
try:
if credential.get("yxt_token"):
client.restore(credential)
else:
client.authorize(client.login())
try:
data = client.home_snapshot()
except SessionExpired:
client.authorize(client.login())
data = client.home_snapshot()
updated = client.export_credential()
if _dump(updated) != _dump(credential):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
finally:
client.close()
def stored_password(account: Account) -> str:
+71 -5
View File
@@ -1,3 +1,5 @@
import json
from fastapi.testclient import TestClient
from sqlalchemy import text
@@ -10,12 +12,61 @@ class FakeClient:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name
self.password = password
self._token = "yxt-1"
self._profile = {
"token": "ucs-1",
"accountId": login_name,
"userId": "u1",
"ssoinfo": "sso",
"unionId": "",
}
def close(self) -> None:
return None
def login(self) -> dict:
return {"accountId": self.login_name}
return dict(self._profile)
def authorize(self, profile: dict) -> None:
self._profile = dict(profile)
def export_credential(self) -> dict:
return {
"ucs_token": self._profile["token"],
"ucs_account_id": self._profile["accountId"],
"ucs_user_id": self._profile["userId"],
"ucs_ssoinfo": self._profile["ssoinfo"],
"ucs_union_id": self._profile["unionId"],
"yxt_token": self._token,
}
def restore(self, credential: dict) -> None:
self._token = credential["yxt_token"]
self._profile = {
"token": credential["ucs_token"],
"accountId": credential["ucs_account_id"],
"userId": credential["ucs_user_id"],
"ssoinfo": credential["ucs_ssoinfo"],
"unionId": credential["ucs_union_id"],
}
def home_snapshot(self) -> dict:
if self._token == "yxt-1":
self._token = "yxt-2"
return {
"name": "测试用户",
"avatar": "https://example.test/a.jpg",
"department": "测试部门",
"level": "Scientist",
"year_score": "1.00",
"month_score": "0.20",
"total_hours": "10",
"total_score": "3.00",
"today_hours": "1",
"today_score": "0.10",
"pending_exam_count": 1,
"pending_exams": [{"name": "安全考试", "deadline": ""}],
}
def setup_function() -> None:
@@ -26,21 +77,36 @@ def setup_function() -> None:
init_db()
def test_login_stores_only_employee_id_and_password() -> None:
def test_login_stores_password_and_credential_only() -> None:
import euniv.api as api_module
import euniv.service as service_module
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
db, employee_id, password, FakeClient
)
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert response.status_code == 200
assert response.json() == {"employee_id": "6650000146"}
listed = client.get("/api/accounts").json()
assert listed == [{"employee_id": "6650000146"}]
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert decrypt_secret(account.password_cipher) == "secret-pass"
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher"}
stored = json.loads(decrypt_secret(account.credential_cipher))
assert stored["yxt_token"] == "yxt-1"
assert stored["ucs_token"] == "ucs-1"
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher", "credential_cipher"}
home = client.get("/api/home", params={"employee_id": "6650000146"})
assert home.status_code == 200
body = home.json()
assert body["name"] == "测试用户"
assert body["pending_exams"] == [{"name": "安全考试", "deadline": ""}]
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
updated = json.loads(decrypt_secret(account.credential_cipher))
assert updated["yxt_token"] == "yxt-2"
assert "测试用户" not in decrypt_secret(account.credential_cipher)
assert "测试用户" not in decrypt_secret(account.password_cipher)
@@ -1,22 +0,0 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { NDataTable } from "naive-ui";
const rows = ref<{ employee_id: string }[]>([]);
const columns = [{ title: "工号", key: "employee_id" }];
onMounted(async () => {
const response = await fetch("/api/accounts");
if (response.ok) rows.value = await response.json();
});
</script>
<template>
<section class="page">
<header class="page-head">
<h2>使用者</h2>
</header>
<n-data-table :columns="columns" :data="rows" :bordered="false" />
</section>
</template>
+115
View File
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NDataTable } from "naive-ui";
interface ExamItem {
name: string;
deadline: string;
}
interface HomeProfile {
name: string;
avatar: string;
department: string;
level: string;
year_score: string;
month_score: string;
total_hours: string;
total_score: string;
today_hours: string | number | null;
today_score: string | number | null;
pending_exam_count: number;
pending_exams: ExamItem[];
}
const props = defineProps<{ employeeId: string }>();
const profile = ref<HomeProfile | null>(null);
const errorText = ref("");
const loading = ref(false);
let timer = 0;
let requestId = 0;
const facts = computed(() => {
const current = profile.value;
if (!current) return [];
return [
{ label: "本年学分", value: current.year_score },
{ label: "本月学分", value: current.month_score },
{ label: "累计学时", value: current.total_hours },
{ label: "累计学分", value: current.total_score },
{ label: "今日学时", value: current.today_hours ?? "—" },
{ label: "今日学分", value: current.today_score ?? "—" },
];
});
const columns = [
{ title: "考试", key: "name" },
{ title: "时间", key: "deadline" },
];
async function load() {
const current = ++requestId;
loading.value = profile.value === null;
try {
const response = await fetch(`/api/home?employee_id=${encodeURIComponent(props.employeeId)}`);
const payload = await response.json().catch(() => ({}));
if (current !== requestId) return;
if (!response.ok) {
errorText.value = typeof payload.detail === "string" ? payload.detail : "首页信息没有获取到,30 秒后会再试。";
return;
}
errorText.value = "";
profile.value = payload;
} catch {
if (current === requestId) errorText.value = "首页信息没有获取到,30 秒后会再试。";
} finally {
if (current === requestId) loading.value = false;
}
}
onMounted(() => {
void load();
timer = window.setInterval(() => void load(), 30000);
});
onUnmounted(() => window.clearInterval(timer));
</script>
<template>
<section class="page">
<header class="page-head">
<div>
<h2>首页</h2>
<p>个人信息每次进入和之后每 30 秒重新获取,不写入本地。</p>
</div>
</header>
<n-alert v-if="errorText && !profile" type="error">{{ errorText }}</n-alert>
<p v-else-if="loading" class="home-status">正在获取</p>
<div v-if="profile" class="home">
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
<div class="profile">
<img v-if="profile.avatar" class="avatar" :src="profile.avatar" alt="" referrerpolicy="no-referrer" />
<div v-else class="brand-mark avatar-fallback" aria-hidden="true">{{ profile.name.slice(0, 1) || "E" }}</div>
<div>
<strong>{{ profile.name || props.employeeId }}</strong>
<span>{{ profile.department }}<template v-if="profile.level"> · {{ profile.level }}</template></span>
</div>
</div>
<dl class="facts">
<div v-for="item in facts" :key="item.label">
<dt>{{ item.label }}</dt>
<dd>{{ item.value }}</dd>
</div>
</dl>
<h3>待考试</h3>
<p class="home-status">{{ profile.pending_exam_count > 0 ? `有 ${profile.pending_exam_count} 场待考试` : "没有待考试" }}</p>
<n-data-table
v-if="profile.pending_exams.length"
:columns="columns"
:data="profile.pending_exams"
:bordered="false"
/>
<p v-else-if="profile.pending_exam_count > 0" class="home-status">清单还没有返回考试名称。</p>
</div>
</section>
</template>
+92 -38
View File
@@ -7,60 +7,114 @@ export interface Scheme {
primary: string;
primaryHover: string;
primaryPressed: string;
danger: string;
vars: Record<string, string>;
}
export const schemes: Scheme[] = [
{
id: "light",
dark: false,
primary: "#2563eb",
primaryHover: "#1d4ed8",
primaryPressed: "#1e40af",
id: "graphite",
dark: true,
primary: "#1F6FEB",
primaryHover: "#388BFD",
primaryPressed: "#1158C7",
danger: "#F85149",
vars: {
"--bg": "#f3f4f6",
"--panel": "#ffffff",
"--ink": "#111827",
"--muted": "#6b7280",
"--line": "#e5e7eb",
"--accent": "#2563eb",
"--accent-soft": "#eff6ff",
"--sidebar": "#ffffff",
"--bg": "#0D1117",
"--panel": "#161A22",
"--elevated": "#1B212B",
"--ink": "#E6EDF3",
"--muted": "#9AA4AE",
"--line": "#262C36",
"--accent": "#79C0FF",
"--accent-soft": "rgba(121, 192, 255, 0.16)",
"--sidebar": "#0D1117",
"--danger": "#F85149",
},
},
{
id: "dark",
dark: true,
primary: "#60a5fa",
primaryHover: "#93c5fd",
primaryPressed: "#3b82f6",
id: "day",
dark: false,
primary: "#1F6FEB",
primaryHover: "#1158C7",
primaryPressed: "#0D419D",
danger: "#CF222E",
vars: {
"--bg": "#0f172a",
"--panel": "#1e293b",
"--ink": "#f8fafc",
"--muted": "#94a3b8",
"--line": "#334155",
"--accent": "#60a5fa",
"--accent-soft": "#1e3a8a",
"--sidebar": "#111827",
"--bg": "#F6F8FA",
"--panel": "#FFFFFF",
"--elevated": "#F6F8FA",
"--ink": "#0D1117",
"--muted": "#57606A",
"--line": "#D0D7DE",
"--accent": "#0969DA",
"--accent-soft": "rgba(9, 105, 218, 0.12)",
"--sidebar": "#FFFFFF",
"--danger": "#CF222E",
},
},
];
const stored = localStorage.getItem("euniv-scheme");
export const schemeId = ref(schemes.some((item) => item.id === stored) ? stored! : "light");
export const schemeId = ref(stored === "day" ? "day" : "graphite");
export const scheme = computed(() => schemes.find((item) => item.id === schemeId.value) ?? schemes[0]);
export const isDark = computed(() => scheme.value.dark);
export const themeOverrides = computed<GlobalThemeOverrides>(() => ({
common: {
primaryColor: scheme.value.primary,
primaryColorHover: scheme.value.primaryHover,
primaryColorPressed: scheme.value.primaryPressed,
primaryColorSuppl: scheme.value.primary,
borderRadius: "6px",
fontFamily: '"Segoe UI", "Microsoft YaHei", sans-serif',
},
}));
export const themeOverrides = computed<GlobalThemeOverrides>(() => {
const current = scheme.value;
return {
common: {
primaryColor: current.primary,
primaryColorHover: current.primaryHover,
primaryColorPressed: current.primaryPressed,
primaryColorSuppl: current.primary,
errorColor: current.danger,
errorColorHover: current.danger,
errorColorPressed: current.danger,
bodyColor: current.vars["--bg"],
cardColor: current.vars["--panel"],
modalColor: current.vars["--panel"],
popoverColor: current.vars["--elevated"],
tableColor: current.vars["--panel"],
inputColor: current.dark ? current.vars["--elevated"] : "#ffffff",
borderColor: current.vars["--line"],
dividerColor: current.vars["--line"],
textColorBase: current.vars["--ink"],
textColor1: current.vars["--ink"],
textColor2: current.vars["--muted"],
textColor3: current.vars["--muted"],
placeholderColor: current.vars["--muted"],
iconColor: current.vars["--muted"],
hoverColor: current.vars["--accent-soft"],
borderRadius: "4px",
fontFamily: '"Segoe UI", "Microsoft YaHei", sans-serif',
},
Button: {
textColorPrimary: "#ffffff",
textColorHoverPrimary: "#ffffff",
textColorPressedPrimary: "#ffffff",
textColorFocusPrimary: "#ffffff",
},
Menu: {
itemTextColor: current.vars["--ink"],
itemIconColor: current.vars["--muted"],
itemTextColorActive: current.vars["--accent"],
itemIconColorActive: current.vars["--accent"],
itemTextColorHover: current.vars["--ink"],
itemIconColorHover: current.vars["--ink"],
itemColorActive: "transparent",
itemColorActiveHover: "transparent",
itemColorActiveCollapsed: "transparent",
itemColorHover: current.vars["--elevated"],
borderRadius: "4px",
},
DataTable: {
thColor: "transparent",
tdColor: "transparent",
borderColor: current.vars["--line"],
thTextColor: current.vars["--muted"],
tdTextColor: current.vars["--ink"],
},
};
});
watch(scheme, (value) => {
localStorage.setItem("euniv-scheme", value.id);
@@ -73,5 +127,5 @@ watch(scheme, (value) => {
}, { immediate: true });
export function toggleTheme() {
schemeId.value = scheme.value.dark ? "light" : "dark";
schemeId.value = scheme.value.dark ? "day" : "graphite";
}
+18 -7
View File
@@ -1,18 +1,25 @@
<script setup lang="ts">
import { ref } from "vue";
import { onMounted, onUnmounted, ref } from "vue";
import { NButton, NIcon, NLayout, NLayoutSider, NMenu, NTooltip } from "naive-ui";
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
import { isDark, toggleTheme } from "../shared/theme";
import { navOptions, type PageKey } from "./navigation";
import AccountsView from "../features/accounts/AccountsView.vue";
import HomeView from "../features/home/HomeView.vue";
const props = defineProps<{ employeeId: string }>();
const emit = defineEmits<{ logout: [] }>();
const page = ref<PageKey>("accounts");
const collapsed = ref(false);
const page = ref<PageKey>("home");
const collapsed = ref(window.innerWidth < 800);
function onResize() {
if (window.innerWidth < 800) collapsed.value = true;
}
onMounted(() => window.addEventListener("resize", onResize));
onUnmounted(() => window.removeEventListener("resize", onResize));
function onMenu(key: string) {
if (key === "accounts") page.value = key;
if (key === "home") page.value = key;
}
</script>
@@ -31,6 +38,10 @@ function onMenu(key: string) {
@expand="collapsed = false"
>
<div class="sider-body">
<div class="sider-brand" :class="{ compact: collapsed }">
<div class="brand-mark" aria-hidden="true">E</div>
<strong v-if="!collapsed">EunivTools</strong>
</div>
<n-menu
:collapsed="collapsed"
:collapsed-width="64"
@@ -55,7 +66,7 @@ function onMenu(key: string) {
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button quaternary circle size="small" aria-label="退出" @click="emit('logout')">
<n-button class="logout-btn" quaternary circle size="small" aria-label="退出" @click="emit('logout')">
<template #icon><n-icon><LogOutOutline /></n-icon></template>
</n-button>
</template>
@@ -65,7 +76,7 @@ function onMenu(key: string) {
</div>
</n-layout-sider>
<n-layout class="content">
<AccountsView v-if="page === 'accounts'" />
<HomeView v-if="page === 'home'" :employee-id="props.employeeId" />
</n-layout>
</n-layout>
</template>
+3 -3
View File
@@ -1,14 +1,14 @@
import type { Component } from "vue";
import { h } from "vue";
import { NIcon } from "naive-ui";
import { PeopleOutline } from "@vicons/ionicons5";
import { HomeOutline } from "@vicons/ionicons5";
function renderIcon(icon: Component) {
return () => h(NIcon, null, { default: () => h(icon) });
}
export type PageKey = "accounts";
export type PageKey = "home";
export const navOptions = [
{ label: "使用者", key: "accounts" as const, icon: renderIcon(PeopleOutline) },
{ label: "首页", key: "home" as const, icon: renderIcon(HomeOutline) },
];
+196 -29
View File
@@ -3,25 +3,29 @@
background: var(--bg);
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
font-size: 14px;
--bg: #f3f4f6;
--panel: #ffffff;
--ink: #111827;
--muted: #6b7280;
--line: #e5e7eb;
--accent: #2563eb;
--accent-soft: #eff6ff;
--sidebar: #ffffff;
--bg: #0d1117;
--panel: #161a22;
--elevated: #1b212b;
--ink: #e6edf3;
--muted: #9aa4ae;
--line: #262c36;
--accent: #79c0ff;
--accent-soft: rgba(121, 192, 255, 0.16);
--sidebar: #0d1117;
--danger: #f85149;
}
:root[data-theme="dark"] {
--bg: #0f172a;
--panel: #1e293b;
--ink: #f8fafc;
--muted: #94a3b8;
--line: #334155;
--accent: #60a5fa;
--accent-soft: #1e3a8a;
--sidebar: #111827;
:root[data-scheme="day"] {
--bg: #f6f8fa;
--panel: #ffffff;
--elevated: #f6f8fa;
--ink: #0d1117;
--muted: #57606a;
--line: #d0d7de;
--accent: #0969da;
--accent-soft: rgba(9, 105, 218, 0.12);
--sidebar: #ffffff;
--danger: #cf222e;
}
::selection {
@@ -29,6 +33,15 @@
color: var(--ink);
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
* {
scrollbar-color: var(--line) transparent;
}
html,
body,
#app,
@@ -66,8 +79,7 @@ select {
width: min(440px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: 0 10px 28px rgba(17, 24, 39, 0.08);
border-radius: 4px;
padding: 28px 28px 22px;
}
@@ -80,23 +92,31 @@ select {
}
.brand-mark {
width: 44px;
height: 44px;
border-radius: 10px;
background: var(--accent);
color: #fff;
width: 28px;
height: 28px;
border-radius: 4px;
border: 1px solid var(--accent);
color: var(--accent);
background: transparent;
display: grid;
place-items: center;
flex: none;
font-size: 22px;
font-weight: 600;
font-size: 15px;
font-weight: 650;
line-height: 1;
}
.gate .brand-mark {
width: 36px;
height: 36px;
font-size: 18px;
}
.brand h1 {
margin: 0;
font-size: 20px;
line-height: 1.3;
letter-spacing: -0.03em;
}
.form-row {
@@ -127,8 +147,15 @@ select {
color: var(--ink);
}
.shell .n-layout,
.shell .n-layout-scroll-container,
.content {
background: var(--bg);
}
.shell .n-layout-sider {
background: var(--sidebar);
border-right: 1px solid var(--line);
}
.shell .n-layout-sider > .n-scrollbar,
@@ -145,9 +172,37 @@ select {
min-height: 0;
}
.sider-brand {
height: 56px;
display: flex;
align-items: center;
gap: 10px;
padding: 0 16px;
border-bottom: 1px solid var(--line);
flex: none;
}
.sider-brand.compact {
justify-content: center;
padding: 0;
}
.sider-brand strong {
font-size: 15px;
font-weight: 650;
letter-spacing: -0.02em;
}
.sider-body .n-menu {
flex: 1;
min-height: 0;
padding-top: 8px;
}
.shell .n-menu .n-menu-item-content--selected::before {
background-color: transparent !important;
border-left: 2px solid var(--accent);
border-radius: 0;
}
.sider-user {
@@ -182,6 +237,18 @@ select {
font-size: 12px;
}
.sider-user strong {
font-variant-numeric: tabular-nums;
}
.logout-btn.n-button {
color: var(--danger);
--n-text-color: var(--danger);
--n-text-color-hover: var(--danger);
--n-text-color-pressed: var(--danger);
--n-text-color-focus: var(--danger);
}
.content {
min-width: 0;
min-height: 0;
@@ -195,18 +262,118 @@ select {
min-height: 0;
display: flex;
flex-direction: column;
padding: 16px 20px;
padding: 28px 32px 20px;
box-sizing: border-box;
}
.page-head {
display: flex;
align-items: center;
align-items: flex-end;
justify-content: space-between;
margin-bottom: 12px;
margin-bottom: 16px;
}
.page-head h2 {
margin: 0 0 6px;
font-size: 22px;
font-weight: 650;
letter-spacing: -0.03em;
}
.page-head p {
margin: 0;
color: var(--muted);
}
.page .n-data-table {
font-variant-numeric: tabular-nums;
}
.page .n-data-table td {
white-space: nowrap;
}
.home {
min-height: 0;
overflow: auto;
}
.profile {
display: flex;
align-items: center;
gap: 14px;
margin-bottom: 16px;
}
.profile strong,
.profile span {
display: block;
}
.profile span {
margin-top: 4px;
color: var(--muted);
}
.avatar,
.avatar-fallback {
width: 48px;
height: 48px;
border-radius: 4px;
}
.avatar {
object-fit: cover;
border: 1px solid var(--line);
}
.avatar-fallback {
font-size: 20px;
}
.facts {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin: 0 0 20px;
border-top: 1px solid var(--line);
border-left: 1px solid var(--line);
}
.facts div {
padding: 12px 16px;
border-right: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.facts dt {
color: var(--muted);
font-size: 12px;
}
.facts dd {
margin: 6px 0 0;
font-size: 22px;
font-weight: 650;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.home h3 {
margin: 0 0 8px;
font-size: 16px;
}
.home-status {
margin: 0 0 12px;
color: var(--muted);
}
@media (max-width: 800px) {
.page {
padding: 16px 12px;
}
.facts {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}