Compare commits

...
Author SHA1 Message Date
long 83e07baa8f fix(admin): 统一后台使用说明、普通金额和报表辅助色 2026-12-02 15:12:02 +08:00
long 772e6d08f8 fix(admin): 统一诊金与提成结算等九页的浅色界面 2026-12-02 14:45:52 +08:00
long fb3a45d120 fix(admin): 恢复挂号统计时间筛选的系统选中颜色 2026-12-02 11:40:21 +08:00
long 58060175d3 fix(admin): 恢复医生看板筛选的公共选中颜色 2026-12-02 11:33:36 +08:00
long 7a0c62bfb6 fix(admin): 统一一诊医生看板与获客助手并修正排行口径显示 2026-12-02 11:27:01 +08:00
long e73e8b1b18 fix(admin): 移除一诊患者和挂号统计的固定装饰绿 2026-12-02 10:57:16 +08:00
long 6d72d6abe7 fix(admin): 收回一诊患者表空操作列并修正零值排行 2026-12-02 10:38:55 +08:00
long 52d5215673 fix(admin): 统一首页业绩卡边框和排行条配色 2026-12-02 10:02:36 +08:00
long d063d2a8fe feat(admin): 统一我的首页与综合转化统计的新版主题 2026-12-02 09:56:13 +08:00
long edfc67e6f6 fix(admin): 折叠时恢复图标栏和右侧悬浮菜单 2026-12-02 09:31:36 +08:00
long 608e912966 fix(admin): 折叠菜单内逐级选页并记住桌面偏好 2026-12-02 09:23:13 +08:00
long e4712895f3 fix(qa): 禁止后台验收启动系统 Google Chrome 2026-12-01 20:20:59 +08:00
long 4101b11aaf feat(admin): 改善工作台和账户消耗的等待、异常与移动体验 2026-12-01 20:01:41 +08:00
long f02d47468b feat(admin): 增加启动与导航反馈并保护工作标签状态 2026-12-01 20:01:40 +08:00
long d8a16b0778 feat(admin): 以固定双列替代桌面二级悬浮菜单 2026-12-01 19:39:25 +08:00
long e8da0054fa feat(admin): 完善自录统计卡片的明暗、移动布局及查询反馈 2026-12-01 18:21:01 +08:00
long 878376a7fc feat(admin): 优化窄屏工作标签及键盘导航 2026-12-01 18:19:18 +08:00
long bfaf51796d fix(admin): 校正侧栏箭头与折叠标志并整理子菜单 2026-12-01 18:16:35 +08:00
long 6ca42f5312 feat(admin): 恢复原生登录与业务路由并移除预览顶栏 2026-12-01 18:06:31 +08:00
long 9fe3bd9bb2 fix(admin): 使用正式账号完整菜单树并统一实时版入口 2026-12-01 17:51:39 +08:00
long d96152da09 feat(admin): 增加本人正式账号的独立只读预览入口 2026-12-01 17:43:21 +08:00
long ff55e1568e feat(admin): 联动用户、预约、排班和部门统计的只读预览 2026-12-01 16:52:47 +08:00
long e1681f8d13 fix(admin): 按 Art Design Pro 源码校准明暗主题与默认设置 2026-12-01 16:40:54 +08:00
long 9024e4b287 feat(admin): 升级后台主题并增加本机只读预览 2026-12-01 16:32:03 +08:00
long c48df2464e docs: 对照 Art Design Pro 源码细化后台换肤步骤 2026-12-01 16:21:22 +08:00
long 1a306211a7 docs: 评估管理后台主题升级范围与风险 2026-12-01 16:15:53 +08:00
183 changed files with 13154 additions and 1481 deletions
+19 -47
View File
@@ -5,51 +5,13 @@
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>后台管理系统</title> <title>后台管理系统</title>
<link rel="stylesheet" href="/admin-loading.css" />
<script defer src="/admin-boot.js"></script>
<style> <style>
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
.preload {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
width: 100vw;
}
.circular {
height: 42px;
width: 42px;
animation: loading-rotate 2s linear infinite;
}
.circular .path {
animation: loading-dash 1.5s ease-in-out infinite;
stroke-dasharray: 90, 150;
stroke-dashoffset: 0;
stroke-width: 2;
stroke: #4073fa;
stroke-linecap: round;
}
@keyframes loading-rotate {
100% {
transform: rotate(1turn);
}
}
@keyframes loading-dash {
0% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -40px;
}
100% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -120px;
}
}
</style> </style>
<script> <script>
// 动态加载 Chat UIKit 样式 // 动态加载 Chat UIKit 样式
@@ -165,13 +127,23 @@
</style> </style>
</head> </head>
<body> <body>
<div id="app"> <div id="admin-boot" data-state="loading">
<div class="preload"> <div>
<svg viewBox="25 25 50 50" class="circular"> <svg class="boot-mark" width="40" height="40" viewBox="0 0 40 40" fill="currentColor" aria-hidden="true">
<circle cx="50" cy="50" r="20" fill="none" class="path"></circle> <circle cx="20" cy="8" r="4"/><circle cx="32" cy="20" r="4" opacity=".76"/>
</svg> <circle cx="20" cy="32" r="4" opacity=".52"/><circle cx="8" cy="20" r="4" opacity=".32"/>
</div> </svg>
</div> <strong>甄养堂管理后台</strong>
<p role="status" aria-atomic="true">
<span data-message="loading">正在打开工作台…</span>
<span data-message="slow">加载时间较长,可继续等待或重新加载。</span>
<span data-message="error">工作台未能打开,请检查网络后重试。</span>
</p>
<a id="admin-boot-retry" href="">重新加载</a>
<noscript>请启用 JavaScript 后重新加载。</noscript>
</div>
</div>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
<script> <script>
// Dify 聊天窗口全屏切换:#dify-chatbot-bubble-window 是 iframe 本身, // Dify 聊天窗口全屏切换:#dify-chatbot-bubble-window 是 iframe 本身,
+1
View File
@@ -0,0 +1 @@
__pycache__/
+23
View File
@@ -0,0 +1,23 @@
# 本机完整后台(正式 API)
入口:<http://127.0.0.1:5179/admin/login>。旧 5178 书签跳到此处。这个入口使用 `src/main.ts`、正式项目前端的路由守卫、用户 Store、完整视图目录、权限指令及请求客户端;不加载 `live-readonly` 的菜单投影、只读请求列表、替代顶栏或 `local-preview` 的合成数据。
菜单、业务数据和操作权限从正式服务取得。顶栏保留全屏、本人账号下拉和设置;界面新旧切换位于设置的「界面样式」。例如「数据统计 → 自录数据统计 → 自录转化统计」直接渲染业务 Vue,可按日期重新查询。空 `paths` 是目录的默认子页,不是无效地址。
登录页读取正式站的公开品牌和登录开关。账号密码登录在本机界面内完成,浏览器使用原生客户端直接请求正式 HTTPS API,依原版在当前浏览器保存会话并执行首次改密、企业微信绑定、菜单/按钮权限等校验。本机静态服务不接收表单/令牌,不连接数据库。企业微信扫码与统一账号快捷登录使用已登记的正式回调,成功后停留在正式域名,不将票据或会话从正式站转送到本地。在本机新版看实时数据请使用账号密码方式。
**这是正式业务,不是只读演示。** 账号获授权的保存、修改、删除、导出等操作会按正式后端的业务规则执行,可能影响线上数据。不要向他人提供密码或 token。
从 `admin` 目录启动(不执行 `release.mjs`、不写发布目录):
```sh
node live-native/build.mjs && node live-native/server.mjs
```
构建输出仅在本工作树 `admin/node_modules/.zyt-live-native/dist`。本机会话任务为 `local.zyt.live-native.bfc2`,可用 `launchctl remove local.zyt.live-native.bfc2` 停止,不设开机启动项。可选 `server.mjs --qa` 使用 5181 供隔离验收。
黑盒检查:`python3 live-native/browser_contract.py --host 127.0.0.1:5179 --out <本地截图目录>`。测试拦截所有非本机请求,仅用虚构登录/统计数据检查真实组件;不验证真实用户凭据或线上写入。
分批 UI 验收:`node live-native/build.mjs v1-example` 只写入本机候选目录;`node live-native/server.mjs --qa v1-example` 在本机 5181 查看它。验收通过后运行 `node live-native/promote-local.mjs apply v1-example`;如需切回上版且当前仍是此构建,运行 `node live-native/promote-local.mjs restore v1-example`。每次应用使用唯一候选名。5179 的旧哈希资源继续可用,不涉及正式发布目录。
浏览器验收仅使用 Playwright 配套的 Chromium Headless Shell,不调用系统 Google Chrome。未安装专用引擎时,跳过浏览器验收;不要指定系统浏览器补跑。
+235
View File
@@ -0,0 +1,235 @@
"""Native admin browser contract. Only loopback static assets leave the test interceptor."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, quote, urlsplit
from playwright.sync_api import expect, sync_playwright
OFFICIAL = "https://admin.zhenyangtang.com.cn"
WX, IAM = "/login/workWechatConfig", "/iam/config"
OVERVIEW, COST = "/stats.self_input/overview", "/stats.personal_account_cost/lists"
LOGIN, SELF, CONFIG = "/login/account", "/auth.admin/mySelf", "/config/getConfig"
ACCOUNT, PASS, TOKEN, USER = "offline-native", "offline-only-password", "fixture-session", "离线验收员"
PROJECTIONS = ["正式数据 · 只读", "刷新线上菜单", "退出预览", "切回旧版"]
BRAND = "data:image/svg+xml," + quote('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><circle cx="8" cy="8" r="6" fill="green"/></svg>')
def loopback(value):
if not re.fullmatch(r"127\.0\.0\.1:[1-9]\d{0,4}", value) or int(value.split(":")[1]) > 65535:
raise argparse.ArgumentTypeError("expected 127.0.0.1:PORT")
return value
def menu(id_, name, path, *, children=None, component="", perm=""):
item = dict(id=id_, type="M" if children else "C", name=name, paths=path, component=component,
perms=perm, params="", icon="", selected="", is_show=1, is_disable=0, is_cache=0)
if children:
item["children"] = children
return item
def profile():
# The empty path is intentional: it is the index child in add_self_input_stats_menu.sql.
overview = menu(303, "自录转化统计", "", component="stats/self_input/index", perm=OVERVIEW[1:])
cost = menu(304, "账户消耗录入", "/account_cost?via=sidebar",
component="stats/self_input/account_cost", perm=COST[1:])
return {"user": {"id": 931, "name": USER, "is_paw": 1, "root": 0, "need_bind_work_wechat": False},
"permissions": [OVERVIEW[1:], COST[1:], "stats.personal_account_cost/add"],
"menu": [menu(301, "数据统计", "/stats", children=[
menu(302, "自录数据统计", "self_input", children=[overview, cost])])]}
class Fixture:
def __init__(self, host, wx, iam):
self.host, self.base = host, f"http://{host}"
self.public = {CONFIG: {"web_name": "后台登录", "version": "fixture", "login_image": BRAND,
"web_logo": BRAND, "copyright_config": []},
WX: {"enabled": wx, "corp_id": "offline-corp" if wx else "", "agent_id": "11" if wx else ""},
IAM: {"enabled": iam, "loginUrl": OFFICIAL + "/adminapi/iam/start" if iam else ""}}
self.reads = {SELF: profile(), "/chat/notifications": [], "/tcm.revisitDue/pending": {"items": [], "summary": {}},
"/tcm.prescription/esignConfig": {"enabled": False}, "/dept.dept/all": [],
"/stats.self_input/mediaSourceOptions": [], COST: {"lists": [], "count": 0, "extend": {}}}
self.calls, self.errors = [], []
self.allowed_handoff, self.documents = set(), []
def route(self, route):
req, url = route.request, urlsplit(route.request.url)
def deny(reason):
# Never print headers, credentials or the query string.
self.errors.append([reason, req.method, url.path])
route.abort()
if (url.scheme, url.netloc) == ("http", self.host):
if req.method == "GET" and (url.path.startswith("/admin/assets/") or
(req.resource_type == "document" and url.path.startswith("/admin/")) or
url.path in ("/favicon.ico", "/admin/favicon.ico", "/admin/admin-loading.css", "/admin/admin-boot.js")):
return route.continue_()
return deny("unexpected local request")
if f"{url.scheme}://{url.netloc}" != OFFICIAL:
return deny("unexpected origin")
if req.resource_type == "document":
if req.method != "GET" or url.path not in self.allowed_handoff or url.query or url.fragment:
return deny("unexpected navigation")
self.allowed_handoff.clear()
self.documents.append(url.path)
return route.fulfill(content_type="text/html", body="<title>Offline official site</title>")
if not url.path.startswith("/adminapi/"):
return deny("unexpected official resource")
path = url.path.removeprefix("/adminapi")
cors = {"Access-Control-Allow-Origin": self.base, "Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "accept,token,version,content-type", "Cache-Control": "no-store"}
if req.method == "OPTIONS":
return route.fulfill(status=204, headers=cors)
self.calls.append([req.method, path])
if req.method == "POST" and path == LOGIN:
if req.post_data_json != {"account": ACCOUNT, "password": PASS, "terminal": 1}:
return deny("unexpected sign-in body")
data = {"token": TOKEN, "is_paw": 1, "need_bind_work_wechat": False}
elif req.method != "GET":
return deny("unexpected mutation")
elif path in self.public:
data = self.public[path]
elif req.headers.get("token") != TOKEN:
return deny("missing fixture session")
elif path == OVERVIEW:
period = parse_qs(url.query).get("time_type", [""])[0]
if period not in ("today", "week"):
return deny("unexpected time range")
data = {"lists": [{"id": 1, "yeji_date": "2026-01-01", "media_source": "OFFLINE-" + period}],
"count": 1, "extend": {"date_range": ["2026-01-01", "2026-01-07"],
"summary": {"add_fans_count": 17 if period == "today" else 31}}}
elif path in self.reads:
data = self.reads[path]
else:
return deny("unknown API")
return route.fulfill(headers=cors, json={"code": 1, "show": 0, "msg": "", "data": data})
def desktop_entry(page, name, root="数据统计", nested="自录数据统计"):
"""Use the visible desktop controls; avoid reselecting a root that is already open."""
rail = page.get_by_role("navigation", name="一级菜单", exact=True)
panel = page.get_by_role("navigation", name="二级菜单", exact=True)
group = rail.get_by_role("button", name=root, exact=True)
if group.get_attribute("aria-expanded") != "true":
group.click()
expect(panel).to_be_visible()
if nested:
branch = panel.get_by_role("button", name=nested, exact=True)
if branch.get_attribute("aria-expanded") != "true":
branch.click()
return panel.get_by_role("link", name=name, exact=True)
def check_app(page, fixture, out):
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
member = page.locator(".app-header").get_by_text(USER, exact=True)
expect(member).to_be_visible(timeout=15000)
expect(page.locator(".app-header [data-admin-ui-toggle]")).to_have_count(0)
for label in PROJECTIONS:
expect(page.locator(".app-header")).not_to_contain_text(label)
member.hover()
for label in ("个人设置", "切换账号", "退出登录"):
expect(page.get_by_text(label, exact=True)).to_be_visible()
page.mouse.move(1, 1)
# First visit the sibling; the empty child below must be selected by click, not just by initial redirect.
desktop_entry(page, "账户消耗录入").click()
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
expect(page.locator("main .personal-account-cost-page").get_by_role("button", name="新增", exact=True)).to_be_visible() # Authorized control is present; never submit any business write.
assert parse_qs(urlsplit(page.url).query).get("via") == ["sidebar"], page.url
desktop_entry(page, "自录转化统计").click()
stats = page.locator("main .self-input-stats-page")
expect(stats.get_by_text("业绩明细", exact=True)).to_be_visible()
expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible()
expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("17")
stats.get_by_text("最近7天", exact=True).click()
expect(stats.locator(".el-table").get_by_text("OFFLINE-week", exact=True)).to_be_visible()
expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("31")
# Native SPA history fallback and dynamic route re-registration must also work on a direct refresh.
page.reload()
expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible()
if out:
page.screenshot(path=str(out / "native-self-input.png"))
assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls
assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN]
def scenario(browser, args, wx, iam):
fixture = Fixture(args.host, wx, iam)
with browser.new_context(service_workers="block", viewport={"width": 1460, "height": 950}) as context:
context.set_default_timeout(8000)
context.route("**/*", fixture.route)
context.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
context.on("page", lambda p: p.on("pageerror", lambda err: fixture.errors.append(str(err))))
page = context.new_page()
try:
page.goto(fixture.base + "/admin/login", wait_until="networkidle")
assert {p for _, p in fixture.calls} == {CONFIG, WX, IAM}, fixture.calls
form = page.locator(".login-card .login-form")
expect(form.get_by_text("后台登录", exact=True)).to_be_visible()
brand = page.locator(".login-card img").filter(visible=True)
expect(brand).to_have_attribute("src", BRAND)
assert brand.evaluate("img => img.complete && img.naturalWidth > 0")
expect(form.get_by_placeholder("请输入账号")).to_be_visible()
expect(form.get_by_placeholder("请输入密码")).to_be_visible()
expect(form.get_by_role("button", name="登录", exact=True)).to_be_visible()
wx_tab = form.get_by_text("企业微信", exact=True)
iam_entry = form.get_by_role("button", name="统一账号快捷登录")
if wx:
expect(wx_tab).to_be_visible()
expect(form.get_by_text("账号登录", exact=True)).to_be_visible()
wx_tab.click()
scan = form.get_by_role("link", name=re.compile("企业微信扫码登录"))
expect(scan).to_be_visible()
dest = urlsplit(scan.get_attribute("href"))
query = parse_qs(dest.query)
assert (dest.scheme, dest.netloc, dest.path) == ("https", "open.work.weixin.qq.com", "/wwopen/sso/qrConnect")
assert query.get("redirect_uri") == [OFFICIAL + "/admin/login"]
assert query.get("appid") == ["offline-corp"] and query.get("agentid") == ["11"]
assert "noopener" in (scan.get_attribute("rel") or "").split()
assert not page.locator("iframe").count() and not fixture.documents
form.get_by_text("账号登录", exact=True).click()
else:
expect(wx_tab).to_be_hidden()
if iam:
expect(iam_entry).to_be_visible()
else:
expect(iam_entry).to_be_hidden()
if wx and iam:
if args.out:
page.screenshot(path=str(args.out / "native-login.png"))
check_app(page, fixture, args.out)
elif iam:
# No real navigation. The interceptor substitutes HTML for the user-initiated GET.
fixture.allowed_handoff.add("/adminapi/iam/start")
with context.expect_event("requestfinished", predicate=lambda r:
r.resource_type == "document" and r.url == OFFICIAL + "/adminapi/iam/start"):
iam_entry.click()
assert fixture.documents == ["/adminapi/iam/start"]
assert not fixture.errors, fixture.errors
except Exception:
print("Failed case:", wx, iam, "mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
raise
return {"wx": wx, "iam": iam, "mocked": fixture.calls}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--out", type=Path, help="Optional directory for offline screenshots")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
]) as browser:
results = [scenario(browser, args, wx, iam) for wx in (False, True) for iam in (False, True)]
print(json.dumps({"native_browser_contract": "PASS", "real_api_calls": 0, "cases": results}, ensure_ascii=False))
+306
View File
@@ -0,0 +1,306 @@
"""Offline black-box checks for the native account-cost form. No business writes leave the fixture."""
import argparse
import json
import re
from datetime import date, timedelta
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, COST, LOGIN, OFFICIAL, PASS, SELF, TOKEN, USER, Fixture, desktop_entry, loopback
PREFIX = "stats.personal_account_cost/"
SOURCE = "线下渠道"
PAGE = ".personal-account-cost-page"
class CostFixture(Fixture):
def __init__(self, host, role):
super().__init__(host, False, False)
perms = self.reads[SELF]["permissions"]
perms.remove(PREFIX + "add")
perms.extend(PREFIX + key for key in {"reader": [], "edit": ["edit"], "delete": ["delete"],
"operator": ["add", "edit", "delete"]}[role])
self.reads["/dept.dept/all"] = [{"id": 42, "name": "验收部门", "children": []}]
self.reads["/stats.self_input/mediaSourceOptions"] = [{"name": SOURCE}]
self.pending = []
self.queries = []
def route(self, route):
req, url = route.request, urlsplit(route.request.url)
if (f"{url.scheme}://{url.netloc}", url.path, req.method) != (OFFICIAL, "/adminapi" + COST, "GET"):
return super().route(route)
if req.headers.get("token") != TOKEN:
self.errors.append("missing fixture session")
return route.abort()
self.calls.append(["GET", COST])
self.pending.append(route)
self.queries.append({k: v[0] for k, v in parse_qs(url.query).items()})
def await_request(self, page, index):
for _ in range(150):
if len(self.queries) > index:
return self.queries[index]
page.wait_for_timeout(30)
raise AssertionError(f"missing cost query #{index + 1}: {self.queries}")
def release(self, page, index, *, amount="128.50", days=1, tag="首条记录", count=1, fail=False):
params = self.await_request(page, index)
route = self.pending[index]
self.pending[index] = None
row = {"id": 11, "cost_date": params["start_date"], "amount": amount, "media_source": SOURCE,
"remark": tag, "creator_name": "验收录入员", "dept_name": "验收部门"}
with page.expect_event("requestfinished", predicate=lambda req: req.url == route.request.url):
route.fulfill(headers={"Access-Control-Allow-Origin": self.base, "Cache-Control": "no-store"},
json={"code": 0 if fail else 1, "msg": "离线失败" if fail else "", "show": 0,
"data": None if fail else {"lists": [row] if count else [], "count": count,
"extend": {"days_count": days, "total_amount": amount}}})
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
def permissions(page, ui, role):
wanted = {"reader": set(), "edit": {"编辑"}, "delete": {"删除"}, "operator": {"新增", "编辑", "删除"}}[role]
for label in ("新增", "编辑", "删除"):
expect(ui.get_by_role("button", name=label, exact=True)).to_have_count(int(label in wanted))
expect(ui.get_by_role("columnheader", name="操作", exact=True)).to_have_count(int(bool(wanted & {"编辑", "删除"})))
if role == "operator":
for label, title in (("新增", "新增账户消耗"), ("编辑", "编辑账户消耗"), ("删除", "确定删除该账户消耗记录?")):
ui.get_by_role("button", name=label, exact=True).click()
dialog = page.get_by_role("dialog")
expect(dialog).to_contain_text(title)
if label == "编辑":
expect(dialog.get_by_placeholder("选填")).to_have_value("首条记录")
dialog.get_by_placeholder("选填").fill("不保存此次修改")
dialog.get_by_role("button", name="取消", exact=True).click()
expect(dialog).not_to_be_visible()
def geometry(ui):
return ui.evaluate("""root => {
const w = document.documentElement.clientWidth;
const shown = [...root.querySelectorAll('.el-radio-button,.el-date-editor,.stats-filter-form .el-select,' +
'.cost-remark-filter .el-input, .el-button, .el-pagination .number')].filter(e => e.getClientRects().length);
const clipped = shown.filter(e => {
const r=e.getBoundingClientRect(); return r.left < -.5 || r.right > w+.5 || r.width < 8;
}).map(e => e.className);
const label = root.querySelector('.cost-remark-filter input'), table=root.querySelector('.el-table__body-wrapper .el-scrollbar__wrap');
const main=root.closest('.el-scrollbar__wrap');
return { width:w, root:root.scrollWidth, rootBox:root.clientWidth, doc:document.documentElement.scrollWidth,
main:main.scrollWidth, mainBox:main.clientWidth, clipped, keyword:label.getBoundingClientRect().width,
table:table.clientWidth, content:table.scrollWidth };
}""")
def shot(page, out, name):
if out:
page.screenshot(path=str(out / f"cost-{name}.png"), animations="disabled")
def reader_checks(page, ui, fx, out, report):
summary = ui.locator(".cost-summary")
rows = ui.locator("tbody tr.el-table__row")
amount, days = summary.locator("dd").first, summary.locator("dd").last
submit = ui.get_by_role("button", name="查询", exact=True)
detail = ui.locator(".el-table__body")
today = date.fromisoformat(fx.await_request(page, 0)["start_date"])
assert fx.queries[0]["end_date"] == today.isoformat()
expect(summary).to_have_attribute("aria-busy", "true")
expect(ui.locator(".cost-skeleton")).to_have_count(2)
expect(ui.get_by_role("status").filter(has_text="加载")).to_be_visible()
assert not re.search(r"\d", summary.inner_text())
assert ui.locator(".cost-skeleton").first.evaluate("e=>getComputedStyle(e).animationName") == "none"
shot(page, out, "first-load")
fx.release(page, 0)
expect(amount).to_have_text("¥128.50")
expect(days).to_have_text("1")
expect(detail).to_contain_text("¥128.50")
permissions(page, ui, "reader")
shot(page, out, "desktop-light")
report.extend(["pending_has_no_false_zero", "api_precision", "read_only_no_operation_column"])
ui.get_by_text("最近7天", exact=True).click()
assert fx.await_request(page, 1)["start_date"] == (today - timedelta(days=6)).isoformat()
ui.get_by_text("昨天", exact=True).click()
assert fx.await_request(page, 2)["start_date"] == (today - timedelta(days=1)).isoformat()
fx.release(page, 2, tag="昨日记录", amount="42.00")
expect(detail).to_contain_text("昨日记录")
fx.release(page, 1, tag="不再显示的旧周报", amount="777.00", days=7)
expect(amount).to_have_text("¥42.00")
expect(detail).to_contain_text("昨日记录")
expect(ui).not_to_contain_text("777.00")
report.append("late_success_ignored")
ui.get_by_text("本月", exact=True).click()
fx.await_request(page, 3)
ui.get_by_text("自定义", exact=True).click()
expect(submit).to_be_disabled()
fx.release(page, 3, fail=True)
expect(rows).to_have_count(0)
expect(amount).to_have_text("—")
expect(ui.get_by_text("请选择开始和结束日期", exact=True)).to_be_visible()
expect(ui.get_by_role("alert")).to_have_count(0)
keyword = ui.get_by_placeholder("备注 / 创建人")
keyword.fill("测试备注")
keyword.press("Enter")
assert len(fx.queries) == 4
ui.get_by_placeholder("开始日期").click()
options = page.locator(".el-date-range-picker__content.is-left:visible td.available")
options.nth(2).click()
options.nth(4).click()
custom = fx.await_request(page, 4)
assert custom["start_date"] == ui.get_by_placeholder("开始日期").input_value()
assert custom["end_date"] == ui.get_by_placeholder("结束日期").input_value()
assert custom["start_date"] < custom["end_date"] and custom["remark"] == "测试备注"
fx.release(page, 4, tag="自定义记录", count=32)
expect(detail).to_contain_text("自定义记录")
report.extend(["incomplete_dates_block_query_and_hide_old_errors", "selected_dates_sent_without_fallback"])
# Keep the active page on retry (a failed second page must not silently send page one).
ui.locator(".cost-pagination .btn-next").click()
assert fx.await_request(page, 5)["page_no"] == "2"
fx.release(page, 5, fail=True)
expect(ui.get_by_role("alert")).to_be_visible()
expect(amount).to_have_text("—")
expect(rows).to_have_count(0)
shot(page, out, "error")
ui.get_by_role("button", name="重新加载", exact=True).click()
assert fx.await_request(page, 6) == fx.queries[5]
fx.release(page, 6, amount="31.10", tag="第二页", count=32)
expect(detail).to_contain_text("第二页")
expect(amount).to_have_text("¥31.10")
report.extend(["failure_no_stale_data", "retry_preserves_page_and_filter"])
ui.locator(".el-form-item").filter(has_text="部门").locator(".el-select__wrapper").click()
page.get_by_role("treeitem").get_by_text("验收部门", exact=True).click()
assert fx.await_request(page, 7)["dept_id"] == "42" and fx.queries[7]["page_no"] == "1"
fx.release(page, 7)
ui.locator(".el-form-item").filter(has_text="自媒体来源").locator(".el-select__wrapper").click()
page.get_by_role("option", name=SOURCE, exact=True).click()
assert fx.await_request(page, 8)["media_source"] == SOURCE
fx.release(page, 8, fail=True)
ui.get_by_role("button", name="重置", exact=True).click()
q = fx.await_request(page, 9)
assert q == fx.queries[0], (q, fx.queries[0])
fx.release(page, 9, amount="0.00", days=0, count=0)
expect(amount).to_have_text("¥0.00")
expect(days).to_have_text("0")
expect(ui.get_by_text("当前筛选下没有消耗记录", exact=True)).to_be_visible()
report.extend(["department_source_filters", "reset_restores_initial_query", "real_zero_and_empty_distinct"])
ui.get_by_text("最近7天", exact=True).click()
fx.await_request(page, 10)
ui.get_by_text("昨天", exact=True).click()
fx.release(page, 11, tag="当前结果", amount=None, days=None)
fx.release(page, 10, fail=True)
expect(detail).to_contain_text("当前结果")
expect(ui.get_by_role("alert")).to_have_count(0)
expect(amount).to_have_text("—")
expect(days).to_have_text("—")
report.extend(["late_failure_ignored", "missing_summary_not_zero"])
light = ui.locator(".cost-results").evaluate("e=>getComputedStyle(e).backgroundColor")
page.emulate_media(color_scheme="dark", reduced_motion="reduce")
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
dark = ui.locator(".cost-results").evaluate("e=>getComputedStyle(e).backgroundColor")
assert light != dark, (light, dark)
shot(page, out, "desktop-dark")
page.set_viewport_size({"width": 390, "height": 844})
expect(page.locator(".app-aside .side")).to_be_hidden()
submit.click()
fx.release(page, 12, amount="1234567890123456.75", tag="窄屏记录")
expect(amount).to_have_text("¥1234567890123456.75")
dims = geometry(ui)
assert not dims["clipped"] and dims["doc"] <= dims["width"] + 1 and dims["root"] <= dims["rootBox"] + 1, dims
assert dims["main"] <= dims["mainBox"] + 1 and dims["content"] > dims["table"] > 0 and dims["keyword"] >= 100, dims
assert amount.evaluate("""e=>{const r=document.createRange();r.selectNodeContents(e);const box=e.getBoundingClientRect();
return [...r.getClientRects()].every(x=>x.right<=box.right+1 && x.bottom<=box.bottom+1);}""")
shot(page, out, "390-dark")
report.extend(["desktop_light_and_dark", "390px_fields_visible_only_table_scrolls", "large_amount_wraps"])
ui.get_by_text("自定义", exact=True).click()
ui.get_by_placeholder("开始日期").click()
picker = page.locator(".el-date-range-picker:visible")
expect(picker).to_be_visible()
picker_box = picker.bounding_box()
assert picker_box["x"] >= 0 and picker_box["x"] + picker_box["width"] <= dims["width"], picker_box
shot(page, out, "390-calendar")
body = picker.locator(".el-picker-panel__body-wrapper")
assert body.evaluate("e=>e.scrollWidth <= e.clientWidth + 1")
assert page.evaluate("document.documentElement.scrollWidth === document.documentElement.clientWidth")
left_dates = picker.locator(".el-date-range-picker__content.is-left td.available")
right_dates = picker.locator(".el-date-range-picker__content.is-right td.available")
left_dates.nth(1).click()
right_dates.nth(3).click()
fx.release(page, 13)
expect(amount).to_have_text("¥128.50")
expect(picker).to_be_hidden()
start, end = ui.get_by_placeholder("开始日期"), ui.get_by_placeholder("结束日期")
committed = (start.input_value(), end.input_value())
assert committed[0][:7] != committed[1][:7] and committed == (fx.queries[13]["start_date"], fx.queries[13]["end_date"])
# Cancel a partial edit: the last applied dates and amount must remain intact.
start.click()
left_dates.nth(2).click()
page.keyboard.press("Escape")
expect(picker).to_be_hidden()
assert committed == (start.input_value(), end.input_value()) and len(fx.queries) == 14
expect(amount).to_have_text("¥128.50")
report.extend(["390px_custom_calendar_across_months", "cancel_partial_range_keeps_applied_dates"])
return dims
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5181")
parser.add_argument("--out", type=Path)
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
report = {"checks": [], "errors": [], "business_writes": [], "fixtures": {}}
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
for role in ("reader", "edit", "delete", "operator"):
fx = CostFixture(args.host, role)
with browser.new_context(service_workers="block", viewport={"width":1280,"height":900},
color_scheme="light", reduced_motion="reduce") as ctx:
ctx.set_default_timeout(6000)
ctx.route("**/*", fx.route)
ctx.route_web_socket("**/*", lambda ws: (fx.errors.append("WebSocket blocked"), ws.close()))
page = ctx.new_page()
page.on("pageerror", lambda err: fx.errors.append(str(err)))
try:
page.goto(fx.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
desktop_entry(page, "账户消耗录入").click()
ui = page.locator("main " + PAGE)
expect(ui).to_be_visible()
if role == "reader":
report["mobile_geometry"] = reader_checks(page, ui, fx, args.out, report["checks"])
else:
fx.release(page, 0)
expect(ui.locator(".el-table__body")).to_contain_text("首条记录")
permissions(page, ui, role)
report["checks"].append("permissions_" + role)
except Exception as err:
report["errors"].append([role, str(err)])
shot(page, args.out, role + "-failure")
finally:
for pending in fx.pending:
if pending is not None:
pending.abort()
report["fixtures"][role] = fx.queries
report["errors"].extend(fx.errors)
report["business_writes"].extend(p for m, p in fx.calls if m not in {"GET", "OPTIONS"} and p != LOGIN)
report["status"] = "FAIL" if report["errors"] or report["business_writes"] else "PASS"
if args.out:
(args.out / "cost-feedback.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n")
print(json.dumps(report, ensure_ascii=False))
return int(report["status"] != "PASS")
if __name__ == "__main__":
raise SystemExit(main())
+195
View File
@@ -0,0 +1,195 @@
"""Cold startup, slow navigation, tab lifetime, recovery and reduced motion. Offline only."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, PASS, USER, SELF, OVERVIEW, LOGIN, TOKEN, Fixture, desktop_entry, loopback, menu
CHROME_ARGS = ["--disable-background-networking","--disable-quic","--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]
def snapshot(page, out, name):
if out:
page.screenshot(path=str(out / (name + ".png")), animations="disabled")
def setup(browser, host, *, dark=False, reduce=False):
fx = Fixture(host, False, False)
pages = fx.reads[SELF]["menu"][0]["children"][0]["children"]
pages.append(menu(409, "复核记录", "review", component="stats/self_input/index"))
for leaf in pages:
leaf["is_cache"] = 1
ctx = browser.new_context(service_workers="block", viewport={"width":1400,"height":900},
color_scheme="dark" if dark else "light", reduced_motion="reduce" if reduce else "no-preference")
ctx.route("**/*", fx.route)
ctx.route_web_socket("**/*", lambda ws: (fx.errors.append("unexpected websocket"),ws.close()))
return ctx,fx,ctx.new_page()
def wait_for_request(page, held):
for _ in range(150):
if held: return
page.wait_for_timeout(25)
raise AssertionError("expected lazy asset was not requested")
def boot(browser, host, out, reduce, fail=False):
ctx, fx, page = setup(browser,host,dark=reduce,reduce=reduce)
held=[]
# Keep the entry pending to allow the first HTML paint; release only to verified loopback assets.
def hold(route):
if (route.request.url.startswith(fx.base+"/admin/assets/") and route.request.resource_type=="script"
and page.url.startswith(fx.base) and not held):
held.append(route)
else: route.fallback()
page.route("**/assets/**",hold)
page.goto(fx.base+"/admin/login",wait_until="commit")
mark=page.locator("#admin-boot")
expect(mark).to_be_visible()
expect(mark.get_by_role("status")).to_contain_text("正在打开")
wait_for_request(page,held)
page.wait_for_function("() => !!document.querySelector('link[href*=\u0022admin-loading.css\u0022]')?.sheet")
motion=mark.locator(".boot-mark").evaluate("e => getComputedStyle(e).animationName")
assert (motion=="none") == reduce,(motion,reduce)
snapshot(page,out,"boot-dark-reduced" if reduce else "boot-light")
if fail:
held[0].abort("failed")
expect(mark).to_have_attribute("data-state","error",timeout=6500)
snapshot(page,out,"boot-error")
page.unroute("**/assets/**",hold)
mark.get_by_role("link",name="重新加载").click()
else:
held[0].continue_()
expect(mark).to_have_count(0,timeout=15000)
expect(page.get_by_placeholder("请输入账号")).to_be_visible()
assert not fx.errors,fx.errors
ctx.close()
return {"motion":motion,"manual_recovery":fail}
def journey(browser,host,out):
ctx,fx,page=setup(browser,host)
page.goto(fx.base+"/admin/login");page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS);page.get_by_role("button",name="登录",exact=True).click()
expect(page.locator(".app-header")).to_contain_text(USER)
stats=page.locator("main .self-input-stats-page");expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
bar=page.locator("#admin-route-progress")
cost="账户消耗录入"; home="自录转化统计"; other="复核记录"
tab=lambda name:page.locator(".app-tabs").get_by_role("tab",name=name,exact=True)
def visit(name):
desktop_entry(page,name).click()
expect(tab(name)).to_have_attribute("aria-selected","true")
def row(period):
expect(stats.get_by_text("OFFLINE-"+period,exact=True)).to_be_visible()
# A real lazy import is held. Existing content and controls must not be covered.
held=[]
def hold_cost(route):
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script" and not held:
held.append(route)
else:route.fallback()
page.route("**/assets/account_cost-*.js",hold_cost)
desktop_entry(page,cost).click()
wait_for_request(page,held)
expect(bar).to_be_visible();expect(bar).to_have_attribute("role","progressbar")
assert bar.evaluate("e=>getComputedStyle(e).pointerEvents")=="none"
expect(stats).to_be_visible()
snapshot(page,out,"route-loading")
held[0].continue_()
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
expect(bar).to_have_count(0);page.unroute("**/assets/account_cost-*.js",hold_cost)
visit(other);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
# Normalize index path by re-entering it from the sidebar.
visit(home);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
reads=lambda:sum(path==OVERVIEW and method=="GET" for method,path in fx.calls)
before=reads()
tab(other).locator(".is-icon-close").click();expect(tab(other)).to_have_count(0)
tab(cost).click();expect(page.locator("main .personal-account-cost-page")).to_be_visible()
refresh=page.get_by_role("button",name="刷新当前页面")
refresh.press("Enter");expect(page.locator("main .personal-account-cost-page")).to_be_visible()
tab(home).click();row("week")
assert reads()==before,("unrelated tab close or refresh refetched the current filter",before,reads())
# A closed tab using the same Vue page must start a new instance when reopened.
visit(other);row("today");assert reads()==before+1
tab(home).click();row("week")
page.evaluate("""() => {window.__bars=0;new MutationObserver(rs=>{for(const r of rs)for(const n of r.addedNodes)
if(n.id==='admin-route-progress')window.__bars++}).observe(document.body,{childList:true})}""")
tab(other).click();row("today");tab(home).click();row("week")
page.wait_for_timeout(300)
assert page.evaluate("window.__bars")==0,"fast cached navigation flashed a loader"
refresh.press("Enter");row("today")
assert not fx.errors,fx.errors
assert [path for method,path in fx.calls if method=="POST"]==[LOGIN]
ctx.close()
return {"slow_route_nonblocking":True,"fast_route_bars":0,"unrelated_refetches":0,"closed_tab_reinitialized":True,"manual_refresh_reinitialized":True}
def failed_page(browser,host,out):
ctx,fx,page=setup(browser,host,dark=True,reduce=True)
page.goto(fx.base+"/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button",name="登录",exact=True).click()
stats=page.locator("main .self-input-stats-page")
expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
stats.get_by_text("最近7天",exact=True).click()
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
original=page.url
held=[]
def deny(route):
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script":
held.append(route)
else:route.fallback()
page.route("**/assets/account_cost-*.js",deny)
desktop_entry(page,"账户消耗录入").click()
wait_for_request(page,held)
bar=page.get_by_role("progressbar",name="正在打开页面")
expect(bar).to_be_visible()
assert bar.evaluate("e=>getComputedStyle(e).animationName")=="none"
held[0].abort("failed")
notice=page.get_by_role("complementary",name="页面加载提示")
expect(notice.get_by_text("页面未能打开",exact=True)).to_be_visible()
expect(bar).to_have_count(0)
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
assert page.url==original
snapshot(page,out,"page-error")
notice.get_by_role("button",name="关闭提示").press("Enter")
expect(notice).to_have_count(0)
desktop_entry(page,"复核记录").click()
expect(page.locator(".app-tabs").get_by_role("tab",name="复核记录")).to_have_attribute("aria-selected","true")
assert not fx.errors,fx.errors
ctx.close()
return {"old_filter_retained":True,"reduced_progress_static":True,"can_continue_without_reload":True}
def protected_startup(browser,host):
found=[]
for mode,target in [("signed_out","login"),("no_menu","403"),("initial_password","change-password"),("binding","bind-work-wechat")]:
ctx,fx,page=setup(browser,host)
if mode!="signed_out":
ctx.add_init_script("if (location.origin==="+json.dumps(fx.base)+")localStorage.setItem('like_admin_token',"+json.dumps(json.dumps({"value":TOKEN,"expire":""}))+")")
if mode=="no_menu": fx.reads[SELF]["menu"]=[]
if mode=="initial_password": fx.reads[SELF]["user"]["is_paw"]=0
if mode=="binding": fx.reads[SELF]["user"]["need_bind_work_wechat"]=True
page.goto(fx.base+"/admin/stats/self_input")
expect(page).to_have_url(re.compile("/admin/"+target+r"(?:\?|$)"),timeout=15000)
expect(page.locator("#admin-boot")).to_have_count(0)
expect(page.locator("main .self-input-stats-page")).to_have_count(0)
assert not fx.errors and not [p for m,p in fx.calls if m=="POST" or p==OVERVIEW],fx.errors
found.append(target);ctx.close()
return found
if __name__=="__main__":
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument("--host",type=loopback,default="127.0.0.1:5179")
ap.add_argument("--out",type=Path)
a=ap.parse_args()
if a.out: a.out.mkdir(parents=True,exist_ok=True)
with sync_playwright() as pw,pw.chromium.launch(headless=True, args=CHROME_ARGS) as browser:
report={"light":boot(browser,a.host,a.out,False),"dark_reduced":boot(browser,a.host,a.out,True,True),
"journey":journey(browser,a.host,a.out),"asset_failure":failed_page(browser,a.host,a.out),"startup_guards":protected_startup(browser,a.host),"real_api_calls":0,"status":"PASS"}
print(json.dumps(report,ensure_ascii=False))
+144
View File
@@ -0,0 +1,144 @@
"""Offline component test: real shared pagination SFC + installed Element Plus, no server or API."""
import argparse
import json
import re
import subprocess
import tempfile
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
ADMIN = Path(__file__).resolve().parents[1]
BUILD = """
import { build } from 'vite'; import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
await build({root:process.cwd(),configFile:false,envFile:false,publicDir:false,
plugins:[vue(),AutoImport({imports:['vue'],dts:false})],
build:{reportCompressedSize:false,lib:{entry:'fixture.js',name:'Fixture',formats:['iife']}}});
"""
FIXTURE = """
import {createApp,reactive,h} from 'vue';
import {ElPagination,ElConfigProvider} from 'element-plus'; import zh from 'element-plus/es/locale/lang/zh-cn';
import Pager from 'ADMIN_PATH/src/components/pagination/index.vue';
import 'element-plus/theme-chalk/index.css';
import 'ADMIN_PATH/src/styles/element.scss'; import 'ADMIN_PATH/src/styles/admin-v2.scss';
const s=window.fixture=reactive({pager:{page:10,size:15,count:150}, props:{}, calls:[]});
createApp({render:()=>h(ElConfigProvider,{locale:zh},()=>h(Pager,{modelValue:s.pager,...s.props,
onChange:()=>s.calls.push([s.pager.page,s.pager.size])}))}).component('ElPagination',ElPagination).mount('#app');
"""
def geometry(page):
return page.locator('.pagination').evaluate("""n => {
const outer=document.getElementById('app').getBoundingClientRect(), nodes=[...n.querySelectorAll(
'.el-pagination__total,.el-pagination__sizes,.btn-prev,.el-pager>li,.btn-next,.el-pagination__jump')];
return {available:outer.width, width:n.getBoundingClientRect().width,
hidden:nodes.filter(e=>!e.getClientRects().length).map(e=>e.className),
clipped:nodes.filter(e=>{let r=e.getBoundingClientRect();return r.width &&
(r.left<outer.left-.51 || r.right>outer.right+.51)}).map(e=>e.className)};
}""")
def run(page, out, baseline):
calls = lambda: page.evaluate('fixture.calls.map(x=>[...x])')
sizes = page.locator('.el-pagination__sizes')
jump = page.locator('.el-pagination__jump input')
prev = page.get_by_role('button', name='上一页')
nxt = page.get_by_role('button', name='下一页')
expect(nxt).to_be_disabled()
assert not calls()
sizes.click()
page.get_by_role('option').filter(has_text='40').click()
expect(page.locator('.el-pager .is-active')).to_have_text('1')
assert calls() == [[1,40]], calls() # Changing size on the last page must not fetch twice.
nxt.press('Enter')
expect(page.locator('.el-pager .is-active')).to_have_text('2')
prev.click()
expect(prev).to_be_disabled()
jump.fill('4')
jump.press('Enter')
expect(nxt).to_be_disabled()
assert calls() == [[1,40],[2,40],[1,40],[4,40]],calls()
page.evaluate('fixture.pager.count=925000;fixture.pager.page=142')
report={}
for name,viewport,width in [('mobile',390,320),('narrow-panel',1120,210),('wide',1300,1000)]:
page.set_viewport_size({'width':viewport,'height':720})
page.locator('#app').evaluate('(n,w)=>n.style.width=w+"px"',width)
page.evaluate('() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))')
report[name]=geometry(page)
if out:
page.locator('#app').screenshot(path=str(out/(name+'.png')))
if not baseline:
assert not report[name]['hidden'] and not report[name]['clipped'],report[name]
expect(prev).to_be_visible()
expect(nxt).to_be_visible()
expect(jump).to_be_visible()
if not baseline:
page.set_viewport_size({'width':390,'height':720})
page.locator('#app').evaluate("n=>n.style.width='210px'")
nxt.press('Enter')
expect(page.locator('.el-pager .is-active')).to_have_text('143')
jump.fill('1')
jump.press('Enter')
expect(prev).to_be_disabled()
assert calls()[-2:]==[[143,40],[1,40]]
# Scoped styling does not override the classic mobile rule.
page.evaluate("document.documentElement.dataset.adminUi='legacy'")
expect(sizes).to_be_hidden()
expect(jump).to_be_hidden()
page.evaluate("document.documentElement.dataset.adminUi='v2'")
# Omitted controls must stay omitted; caller's custom option list/order is authoritative.
page.evaluate("fixture.props={layout:'next, prev, sizes',pageSizes:[40,60]}")
expect(page.locator('.el-pager')).to_have_count(0)
expect(jump).to_have_count(0)
tags=page.locator('.el-pagination').evaluate("n=>[...n.children].map(e=>e.className)")
assert 'btn-next' in tags[0] and 'btn-prev' in tags[1] and '__sizes' in tags[2],tags
custom=geometry(page)
assert not custom['clipped'] and not custom['hidden'],custom
before=calls()
sizes.click()
options=page.get_by_role('option')
assert options.count()==2
assert [re.match(r'\d+', t.strip()).group() for t in options.all_text_contents()]==['40','60']
options.nth(1).click()
expect(prev).to_be_disabled()
assert calls()==before+[[1,60]],calls()
return dict(layout=report,calls=calls())
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--baseline',action='store_true',help='record pre-change geometry without enforcing a pass')
ap.add_argument('--out',type=Path)
args=ap.parse_args()
if args.out: args.out.mkdir(exist_ok=True,parents=True)
with tempfile.TemporaryDirectory(prefix='zyt-pagination-') as tmp:
root=Path(tmp)
(root/'node_modules').symlink_to(ADMIN/'node_modules',target_is_directory=True)
(root/'build.mjs').write_text(BUILD)
(root/'fixture.js').write_text(FIXTURE.replace('ADMIN_PATH',ADMIN.as_posix()))
(root/'package.json').write_text('{"name":"pager-check","type":"module"}')
subprocess.run(['node','build.mjs'],cwd=root,check=True,stdout=subprocess.DEVNULL)
dist=root/'dist'
with sync_playwright() as pw:
browser=pw.chromium.launch(headless=True,
args=['--disable-background-networking'])
page=browser.new_page()
errors,requests=[],[]
page.on('pageerror',lambda e: errors.append(str(e)))
page.on('request',lambda req: requests.append(req.url))
page.route('**/*',lambda r:r.abort())
page.set_content('<html data-admin-ui="v2"><body><main id="app" style="width:1000px;display:flex;justify-content:flex-end"></main></body></html>')
page.add_style_tag(content=next(dist.glob('*.css')).read_text())
page.evaluate("window.process={env:{NODE_ENV:'production'}}")
page.add_script_tag(content=next(dist.glob('*.js')).read_text())
result=run(page,args.out,args.baseline)
assert not errors and not requests,(errors,requests)
print(json.dumps(result,ensure_ascii=False))
browser.close()
if __name__=='__main__': main()
+615
View File
@@ -0,0 +1,615 @@
"""Offline native sidebar geometry and navigation; requires the prebuilt loopback static server."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, BRAND, LOGIN, PASS, SELF, USER, Fixture, loopback, menu
ROOT = "数据统计"
NESTED = "自录数据统计与跨部门综合分析报表导航"
LEAF = "账户消耗录入与跨部门财务对账明细"
OTHER = "运营管理与跨部门协作流程工作中心"
TOP_LEAF = "独立账户消耗录入"
HOME = "自录转化统计"
DETAIL = "运营明细"
HIDDEN = "仅后台可见明细"
HIDDEN_ROOT = "隐藏目录"
NAMES = "业务报表"
SIMILAR = ("全院财务结算与跨部门对账月报表", "全院财务退款与跨部门对账月报表")
DUPLICATE = "回访明细"
TITLE = ".el-sub-menu__title"
POPUP = ".admin-nav-popper.el-menu--popup-container > .el-menu--popup:visible"
def setup_menu(fixture):
roots = fixture.reads[SELF]["menu"]
root, = roots
nested, = root["children"]
root["icon"] = "el-icon-Setting"
nested.update(name=NESTED, icon="el-icon-Folder")
# A real index child has an empty path. Its defaults must not disappear
# when normalizing the trailing slash or when restoring a work tab.
nested["children"][0]["params"] = '{"via":"index","dept":"QA 组"}'
nested["children"][1].update(name=LEAF, icon="el-icon-Document")
hidden = dict(menu(412, HIDDEN, "hidden", component="stats/self_input/account_cost"), is_show=0)
roots.append(menu(410, OTHER, "operations", children=[
hidden, menu(411, DETAIL, "details?team=ops", component="stats/self_input/account_cost")]))
roots.append(dict(menu(420, TOP_LEAF, "solo", component="stats/self_input/account_cost"),
icon="local-icon-dingdan"))
roots.append(dict(menu(430, HIDDEN_ROOT, "hidden-root", children=[
menu(431, "隐藏目录的明细", "not-listed", component="stats/self_input/account_cost")]), is_show=0))
roots.append(menu(440, NAMES, "reports", children=[
menu(i, name, f"r{i}", component="stats/self_input/account_cost")
for i, name in enumerate([*SIMILAR, DUPLICATE, DUPLICATE], start=441)
]))
# The source of visibility is the returned menu tree, not the table's business-button permissions.
fixture.reads[SELF]["permissions"].remove("stats.personal_account_cost/add")
def settle(element):
# Vue starts CSS transitions on the next animation frames. Don't measure halfway through.
element.evaluate("""async el => {
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
await frame(); await frame();
const anims = el.getAnimations({subtree: true}).filter(a =>
a.effect?.getComputedTiming().endTime < Infinity);
await Promise.allSettled(anims.map(a => a.finished)); await frame();
}""")
def title(parent, name):
return parent.locator(TITLE).filter(has=parent.page.get_by_text(name, exact=True))
def toggle(group_title, opened):
item = group_title.locator("..")
if item.get_attribute("aria-expanded") != str(opened).lower():
group_title.click()
expect(item).to_have_attribute("aria-expanded", str(opened).lower())
settle(item)
def label_metrics(row, name):
return row.get_by_text(name, exact=True).evaluate("""el => {
const range = document.createRange(); range.selectNodeContents(el);
const text = range.getBoundingClientRect(), box = el.getBoundingClientRect();
// Text can extend beyond its range of painted pixels when an ancestor clips it.
let right = text.right, ellipsis = false;
const row = el.closest('.el-menu-item,.el-sub-menu__title');
for (let p = el; p && p !== row; p = p.parentElement) {
const s = getComputedStyle(p);
if (s.overflowX !== 'visible') {
right = Math.min(right, p.getBoundingClientRect().right);
ellipsis ||= s.textOverflow === 'ellipsis';
}
}
return {left: text.left, right, textRight: text.right, ellipsis, height: box.height}
}""")
def arrow_metrics(row, name):
label = label_metrics(row, name)
arrow = row.locator(".el-sub-menu__icon-arrow svg")
expect(arrow).to_be_visible()
result = arrow.evaluate(r"""svg => {
const r = svg.getBoundingClientRect();
const row = svg.closest('.el-sub-menu__title'), b = row.getBoundingClientRect();
const x = r.x + r.width / 2, y = r.y + r.height / 2;
// A zero-sized path, transparent paint, clipped SVG or covered row isn't a visible arrow.
const painted = Array.from(svg.querySelectorAll('path,polygon,polyline,line,use')).some(p => {
const ink = getComputedStyle(p), bounds = p.getBoundingClientRect();
return bounds.width > 1 && bounds.height > 1 && ink.visibility === 'visible' &&
ink.display !== 'none' && [ink.fill, ink.stroke].some(c =>
c && c !== 'none' && c !== 'transparent' && !/rgba\(.*?,\s*0\)$/.test(c));
});
let opacity = 1; for (let p = svg; p; p = p.parentElement) opacity *= +getComputedStyle(p).opacity;
return {left:r.left, right:r.right, end:b.right, width:r.width, painted, opacity,
hit:row.contains(document.elementFromPoint(x,y))};
}""")
assert result["painted"] and result["hit"] and result["opacity"] > .5, (name, result)
assert result["width"] >= 8 and -1 <= result["end"] - result["right"] <= 28, (name, result)
assert label["height"] > 0 and label["left"] < label["right"] <= result["left"] - 1, (name, label, result)
assert label["textRight"] <= label["right"] + 1 or label["ellipsis"], (name, label)
return result["right"]
def expanded(menu_el):
r, n, o = (title(menu_el, name) for name in (ROOT, NESTED, OTHER))
toggle(r, True)
toggle(n, True)
leaf = menu_el.get_by_role("menuitem", name=LEAF, exact=True)
expect(leaf).to_be_visible()
rights = [arrow_metrics(row, name) for row, name in [(r, ROOT), (n, NESTED), (o, OTHER)]]
assert max(rights) - min(rights) <= 1.5, ("arrow right track", rights)
levels = [label_metrics(row, name)["left"] for row, name in [(r, ROOT), (n, NESTED), (leaf, LEAF)]]
assert levels[0] + 4 < levels[1] and levels[1] + 4 < levels[2], ("label indentation", levels)
return dict(arrow_right=rights, label_left=levels)
def center(rail, target, name):
expect(target).to_be_visible()
a, b = rail.bounding_box(), target.bounding_box()
expected, actual = a["x"] + a["width"] / 2, b["x"] + b["width"] / 2
assert abs(expected - actual) <= 1.5, (name, "rail center", expected, "element center", actual)
return round(actual, 2)
def screenshot(page, out, name):
if out:
page.screenshot(path=str(out / f"sidebar-{name}.png"), animations="disabled")
def settings(page):
page.locator(".app-header .setting").click()
drawer = page.get_by_role("dialog", name="主题设置")
expect(drawer.get_by_text("菜单栏宽度", exact=True)).to_be_visible()
return drawer
def close_settings(page, drawer):
page.keyboard.press("Escape")
expect(drawer).to_be_hidden()
def route_at(page, path, query=None, *, trailing=False):
# Require the actual browser address (and all its parameters), not only a Vue component.
expected = "/admin/" + path
expect(page).to_have_url(re.compile(re.escape(expected) + ("" if trailing else "/?") + r"(?:\?.*)?$"))
parts = urlsplit(page.url)
if query is not None:
assert parse_qs(parts.query) == query, (path, query, parts.query)
def layout(page, rail, panel=None, *, expected_width=None):
settle(page.locator(".layout-default"))
rb = rail.bounding_box()
pb = panel.bounding_box() if panel is not None else None
edge = rb["x"] + rb["width"]
if pb:
assert abs(pb["x"] - edge) <= 2, ("gap/overlap between rails", rb, pb)
assert abs(pb["width"] - expected_width) <= 1, ("fixed second panel", pb, expected_width)
edge = pb["x"] + pb["width"]
main = page.locator("main").bounding_box()
header = page.locator(".app-header").bounding_box()
for el in (main, header):
assert abs(el["x"] - edge) <= 2, ("content overlaps or leaves blank space", edge, el)
assert abs(el["x"] + el["width"] - page.viewport_size["width"]) <= 2, el
return {k: round(v, 1) for k, v in {
"rail": rb["width"], "panel": pb["width"] if pb else 0, "main_x": main["x"]}.items()}
def compact_layout(page, rail, panel, fold, baseline=None):
expect(rail).to_be_visible()
expect(fold).to_have_attribute("aria-expanded", "false")
expect(panel).to_be_hidden()
metrics = layout(page, rail)
assert abs(metrics["rail"] - 64) <= 1, ("compact rail", metrics)
assert abs(metrics["main_x"] - 64) <= 2, ("main should start next to the rail", metrics)
if baseline is not None:
assert metrics == baseline, ("opening a flyout or resizing moved the content", metrics, baseline)
return metrics
def icon_only(row, name):
# Count painted text within the row, not textContent: Element keeps accessible
# names for controls whose visual label is hidden. A fallback initial is an icon.
expect(row).to_have_accessible_name(name)
visible = row.evaluate("""row => {
const walk = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
const rect = row.getBoundingClientRect(), words = [];
for (let n; (n = walk.nextNode());) {
if (!n.textContent.trim() || n.parentElement.closest('.menu-item-icon,svg')) continue;
const range = document.createRange(); range.selectNodeContents(n);
const r = range.getBoundingClientRect();
if (r.width < 1 || r.height < 1) continue;
const x = Math.max(r.left, rect.left), y = Math.max(r.top, rect.top);
if (x >= Math.min(r.right, rect.right) || y >= Math.min(r.bottom, rect.bottom)) continue;
if (n.parentElement.checkVisibility({opacityProperty: true, visibilityProperty: true}))
words.push(n.textContent.trim());
}
return words;
}""")
assert visible == [], ("compact rail must contain icons only", name, visible)
def popup_box(row, anchor):
# A child that opens in place would also be visible. Verify it is painted to
# the right of its own trigger, within the viewport, not clipped by a rail.
expect(row).to_be_visible()
box = row.locator("xpath=ancestor::ul[contains(@class,'el-menu--popup')][1]")
settle(box.locator("xpath=ancestor::*[contains(concat(' ',normalize-space(@class),' '),' el-popper ')][1]"))
b, a = box.bounding_box(), anchor.bounding_box()
assert a["x"] + a["width"] - 2 <= b["x"] <= a["x"] + a["width"] + 32, (a, b)
assert b["x"] + b["width"] <= row.page.viewport_size["width"] + 1, b
assert row.evaluate("""e => {
const r = e.getBoundingClientRect();
return e.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2));
}"""), "floating menu row is covered or clipped"
return {k: round(v, 1) for k, v in b.items()}
def clipped(row, selector, label):
el = row.locator(selector)
expect(row).to_have_accessible_name(label)
expect(row).to_have_attribute("title", label)
m = el.evaluate("""e => {
const r = e.getBoundingClientRect(), row = e.closest('button,a').getBoundingClientRect();
return {w:e.clientWidth, full:e.scrollWidth, style:getComputedStyle(e).textOverflow,
inside:r.left >= row.left && r.right <= row.right + 1};
}""")
assert 0 < m["w"] < m["full"] and m["style"] == "ellipsis" and m["inside"], (label, m)
return m
def painted_bg(box):
return box.evaluate("""el => {
for (let p = el; p; p = p.parentElement) {
const c = getComputedStyle(p).backgroundColor.match(/[0-9.]+/g)?.map(Number);
if(c && (c.length === 3 || c[3] >= 0.99)) return c.slice(0,3);
}
return [255,255,255];
}""")
def check(page, fixture, out):
page.goto(fixture.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2")
rail = page.get_by_role("navigation", name="一级菜单", exact=True)
compact = page.get_by_role("navigation", name="折叠菜单", exact=True)
panel = page.get_by_role("navigation", name="二级菜单", exact=True)
root = rail.get_by_role("button", name=ROOT, exact=True)
other = rail.get_by_role("button", name=OTHER, exact=True)
solo = rail.get_by_role("link", name=TOP_LEAF, exact=True)
branch = panel.get_by_role("button", name=NESTED, exact=True)
home = panel.get_by_role("link", name=HOME, exact=True)
cost = panel.get_by_role("link", name=LEAF, exact=True)
detail = panel.get_by_role("link", name=DETAIL, exact=True)
fold = page.locator(".app-header .fold")
tab = lambda name: page.locator(".app-tabs").get_by_role("tab", name=name, exact=True)
h_path, h_query = "stats/self_input", {"via": ["index"], "dept": ["QA 组"]}
c_path, c_query = "stats/self_input/account_cost", {"via": ["sidebar"]}
d_path, d_query = "operations/details", {"team": ["ops"]}
def selected(group, leaf):
expect(rail.locator(".is-active")).to_have_count(1)
expect(group).to_have_class(re.compile(r"\bis-active\b"))
expect(leaf).to_have_attribute("aria-current", "page")
route_at(page, h_path + "/", trailing=True)
expect(tab(HOME)).to_have_count(1)
expect(home).to_be_visible()
selected(root, home)
expect(rail.get_by_text(HIDDEN_ROOT, exact=True)).to_have_count(0)
report = {"expanded": layout(page, rail, panel, expected_width=230)}
for width in (1216, 1440):
page.set_viewport_size({"width": width, "height": 960})
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
logo = rail.locator(".logo img")
expect(logo).to_have_attribute("src", BRAND)
assert logo.evaluate("img => img.complete && img.naturalWidth > 0")
center(rail, logo, "logo")
report["long_labels"] = [clipped(other, ".dual-root-label", OTHER),
clipped(branch, ".dual-label", NESTED), clipped(cost, ".dual-label", LEAF)]
tag = branch.locator(".dual-label").bounding_box()
arrow = branch.locator(".dual-chevron")
expect(arrow).to_be_visible()
assert tag["x"] + tag["width"] < arrow.bounding_box()["x"]
assert cost.locator(".dual-label").bounding_box()["x"] > tag["x"] + 4
screenshot(page, out, "expanded")
# Mouse movements must not navigate, replace a selected root, or close the persistent panel.
other.hover()
page.locator("main").hover()
page.wait_for_timeout(650) # Longer than Element Plus's legacy hover/flyout close delay.
expect(home).to_be_visible()
selected(root, home)
expect(page.locator(".el-menu--popup:visible")).to_have_count(0)
# Traverse the actual second/third level from the button, not simulated router pushes.
branch.focus()
orientation = "el => getComputedStyle(el).transform"
opened_angle = arrow.evaluate(orientation)
page.keyboard.press("Enter")
expect(branch).to_have_attribute("aria-expanded", "false")
expect(cost).to_be_hidden()
settle(branch)
assert opened_angle != arrow.evaluate(orientation), "directory chevron did not change direction"
page.keyboard.press("Space")
expect(branch).to_have_attribute("aria-expanded", "true")
page.keyboard.press("Tab")
expect(home).to_be_focused()
page.keyboard.press("Tab")
expect(cost).to_be_focused()
page.keyboard.press("Enter")
route_at(page, c_path, c_query)
selected(root, cost)
cost_page = page.locator("main .personal-account-cost-page")
expect(cost_page).to_be_visible()
expect(cost_page.get_by_role("button", name="新增", exact=True)).to_have_count(0)
# The startup redirect includes a final slash; the clicked index child omits it.
# Only one work tab survives this normalization, keeping its latest query intact.
home.click()
route_at(page, h_path, h_query, trailing=True)
expect(tab(HOME)).to_have_count(1)
expect(tab(HOME)).to_have_attribute("aria-selected", "true")
selected(root, home)
other.click()
route_at(page, d_path, d_query)
selected(other, detail)
expect(panel.get_by_text(HIDDEN, exact=True)).to_have_count(0)
expect(branch).to_have_count(0)
expect(cost_page).to_be_visible()
expect(detail).to_be_visible()
page.go_back()
route_at(page, h_path, h_query)
selected(root, home)
page.go_forward()
route_at(page, d_path, d_query)
selected(other, detail)
tab(HOME).click()
route_at(page, h_path, h_query)
selected(root, home)
tab(DETAIL).click()
route_at(page, d_path, d_query)
selected(other, detail)
page.reload()
route_at(page, d_path, d_query)
selected(other, detail)
expect(cost_page).to_be_visible()
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
solo.click()
route_at(page, "solo", {})
expect(solo).to_have_attribute("aria-current", "page")
expect(cost_page).to_be_visible()
expect(panel).to_be_hidden()
report["direct_leaf"] = layout(page, rail)
root.click()
route_at(page, h_path, h_query)
selected(root, home)
expect(fold).to_have_attribute("aria-expanded", "true")
fold.press("Enter")
report["collapsed"] = compact_layout(page, compact, panel, fold)
def unchanged():
return compact_layout(page, compact, panel, fold, report["collapsed"])
popups = page.locator(POPUP)
group = lambda name: compact.get_by_role("menuitem", name=name, exact=True)
entry = lambda name: popups.get_by_role("link", name=name, exact=True)
top_leaf = compact.get_by_role("link", name=TOP_LEAF, exact=True)
def only_roots():
expect(compact.get_by_role("menuitem")).to_have_count(4)
for name in (ROOT, OTHER, TOP_LEAF, NAMES):
icon_only(group(name), name)
expect(compact.get_by_role("button", name=re.compile("返回"))).to_have_count(0)
expect(group(NESTED)).to_have_count(0)
expect(group(HIDDEN_ROOT)).to_have_count(0)
def leave_menus():
page.mouse.move(page.viewport_size["width"] - 12, page.viewport_size["height"] - 12)
expect(popups).to_have_count(0)
page.set_viewport_size({"width": 1350, "height": 960})
unchanged()
only_roots()
expect(popups).to_have_count(0)
report["collapsed_centers"] = {"logo": center(compact, compact.locator(".logo img"), "brand image")}
for name in (ROOT, OTHER, TOP_LEAF):
icon = group(name).locator(".menu-item-icon")
report["collapsed_centers"][name] = center(compact, icon, name)
initial = group(OTHER).locator(".menu-item-icon")
assert initial.evaluate("""e => e.querySelector('svg') !== null || !!e.textContent.trim() ||
!['none','normal','""'].includes(getComputedStyle(e, '::before').content)"""), "missing fallback icon"
screenshot(page, out, "collapsed")
# Hover previews groups without navigating. Full labels and distinct link targets
# remain available in the flyout rather than abbreviated or wrapped in the rail.
group(NAMES).hover()
for name in SIMILAR:
expect(entry(name).get_by_text(name, exact=True)).to_be_visible()
twins = popups.get_by_role("link", name=re.compile("^" + DUPLICATE))
expect(twins).to_have_count(2)
assert twins.nth(0).get_attribute("href") != twins.nth(1).get_attribute("href")
route_at(page, h_path, h_query)
unchanged()
group(OTHER).hover()
report["single_level_popup"] = popup_box(entry(DETAIL), group(OTHER))
expect(twins).to_have_count(0)
expect(entry(HIDDEN)).to_have_count(0)
entry(DETAIL).hover()
page.wait_for_timeout(650) # Hold the pointer in the popper beyond the menu's leave delay.
expect(entry(DETAIL)).to_be_visible()
route_at(page, h_path, h_query)
only_roots()
unchanged()
leave_menus()
route_at(page, h_path, h_query)
unchanged()
# The next level is another flyout, not a replacement list or an expanded aside.
group(ROOT).hover()
nested = title(popups, NESTED)
report["second_level_popup"] = popup_box(nested, group(ROOT))
arrow_metrics(nested, NESTED)
expect(entry(LEAF)).to_be_hidden()
nested.hover()
leaf = entry(LEAF)
report["third_level_popup"] = popup_box(leaf, nested)
leaf.hover()
page.wait_for_timeout(650)
expect(leaf).to_be_visible()
expect(nested).to_be_visible()
expect(popups).to_have_count(2)
only_roots()
route_at(page, h_path, h_query)
unchanged()
screenshot(page, out, "collapsed-third-level")
leaf.click()
route_at(page, c_path, c_query)
expect(cost_page).to_be_visible()
expect(popups).to_have_count(0)
only_roots()
unchanged()
# Visit a nested index (empty path with default params), a direct root leaf, then
# a single-child directory using the exact router links the collapsed sidebar displays.
group(ROOT).hover()
nested.hover()
entry(HOME).click()
route_at(page, h_path, h_query, trailing=True)
expect(tab(HOME)).to_have_count(1)
expect(popups).to_have_count(0)
unchanged()
top_leaf.click()
route_at(page, "solo", {})
expect(top_leaf).to_have_attribute("aria-current", "page")
unchanged()
group(OTHER).hover()
route_at(page, "solo", {})
entry(DETAIL).click()
route_at(page, d_path, d_query)
expect(cost_page).to_be_visible()
expect(popups).to_have_count(0)
unchanged()
page.reload()
route_at(page, d_path, d_query)
expect(cost_page).to_be_visible()
expect(popups).to_have_count(0)
only_roots()
unchanged()
# The mobile drawer starts closed, performs real link navigation, then closes. Neither
# opening it nor choosing a link changes the desktop preference saved by the fold button.
group(OTHER).hover()
expect(entry(DETAIL)).to_be_visible()
page.set_viewport_size({"width": 390, "height": 844})
expect(popups).to_have_count(0)
expect(compact).to_be_hidden()
expect(rail).to_be_hidden()
expect(panel).to_be_hidden()
mobile = page.locator(".el-drawer:visible .side")
expect(mobile).to_be_hidden()
fold.click()
expect(mobile).to_be_visible()
settle(mobile.locator("xpath=ancestor::*[contains(@class, 'el-overlay')][1]"))
report["mobile_drawer"] = expanded(mobile.locator(".menu"))
screenshot(page, out, "mobile")
mobile.get_by_role("link", name=LEAF, exact=True).click()
expect(mobile).to_be_hidden()
route_at(page, c_path, c_query)
expect(cost_page).to_be_visible()
page.set_viewport_size({"width": 1440, "height": 960})
unchanged()
# Only the explicit header control restores the wide, fixed second column.
fold.press("Enter")
expect(fold).to_have_attribute("aria-expanded", "true")
expect(compact).to_be_hidden()
selected(root, cost)
route_at(page, c_path, c_query)
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
page.reload()
selected(root, cost)
expect(fold).to_have_attribute("aria-expanded", "true")
assert layout(page, rail, panel, expected_width=230) == report["expanded"]
drawer = settings(page)
logo_item = drawer.locator(".setting-item").filter(has_text="显示LOGO")
logo_item.locator(".el-switch__core").click()
expect(logo_item.get_by_role("switch")).not_to_be_checked()
drawer.get_by_role("button", name="深色菜单").click()
width = drawer.get_by_role("spinbutton")
width.fill("180")
width.press("Enter")
close_settings(page, drawer)
root.click()
selected(root, home)
expect(logo).to_be_hidden()
fallback = rail.locator(".admin-nav-heading svg")
center(rail, fallback, "no-logo icon")
report["dark_180px"] = layout(page, rail, panel, expected_width=180)
report["dark_rgb"] = [painted_bg(rail), painted_bg(panel)]
assert all(max(rgb) < 145 for rgb in report["dark_rgb"]), report["dark_rgb"]
screenshot(page, out, "dark-180")
# Resize with the drawer *open*: Element Plus emits update:modelValue(false)
# after its leave animation, by which time the desktop sidebar is visible again.
page.set_viewport_size({"width": 390, "height": 844})
expect(rail).to_be_hidden()
expect(mobile).to_be_hidden()
fold.click()
expect(mobile).to_be_visible()
settle(mobile.locator("xpath=ancestor::*[contains(@class, 'el-overlay')][1]"))
page.set_viewport_size({"width": 1440, "height": 960})
expect(mobile).to_be_hidden()
settle(page.locator(".layout-default"))
expect(fold).to_have_attribute("aria-expanded", "true")
selected(root, home)
assert layout(page, rail, panel, expected_width=180) == report["dark_180px"]
# Switch through the user's settings, not injected CSS/localStorage.
cost.click()
route_at(page, c_path, c_query)
drawer = settings(page)
drawer.get_by_text("经典", exact=True).click()
close_settings(page, drawer)
expect(page.locator("html")).to_have_attribute("data-admin-ui", "legacy")
expect(rail).to_be_hidden()
expect(panel).to_be_hidden()
tree = page.locator(".app-aside .menu--classic:visible")
toggle(title(tree, ROOT), True)
toggle(title(tree, NESTED), True)
tree.get_by_role("link", name=HOME, exact=True).click()
route_at(page, h_path, h_query)
expect(page.locator("main .self-input-stats-page")).to_be_visible()
screenshot(page, out, "classic")
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--out", type=Path, help="Optional local screenshots directory")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
fixture = Fixture(args.host, False, False)
setup_menu(fixture)
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
with browser.new_context(service_workers="block", viewport={"width": 1440, "height": 960},
color_scheme="light") as ctx:
ctx.set_default_timeout(8000)
ctx.route("**/*", fixture.route)
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
ctx.on("page", lambda p: p.on("pageerror", lambda e: fixture.errors.append(str(e))))
page = ctx.new_page()
try:
report = check(page, fixture, args.out)
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN], fixture.calls
assert not fixture.errors, fixture.errors
except Exception:
screenshot(page, args.out, "failure")
print("mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
raise
print(json.dumps({"sidebar": "PASS", "real_api_calls": 0, **report}, ensure_ascii=False))
if __name__ == "__main__":
main()
+352
View File
@@ -0,0 +1,352 @@
"""Self-input stats visual/data contract. Only loopback static assets reach the network."""
import argparse
import io
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from PIL import Image
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, OVERVIEW, PASS, SELF, TOKEN, USER, Fixture, desktop_entry, loopback
SOURCE = "离线验收来源"
PERMS = {"edit": "stats.personal_yeji/edit", "delete": "stats.personal_yeji/delete"}
PAGE = "main .self-input-stats-page"
EMPTY = re.compile(r"^(?:[-–—―]+|暂无(?:数据)?|未(?:提供|返回|统计)|无数据|N/A)$", re.I)
class StatsFixture(Fixture):
def __init__(self, host, role):
super().__init__(host, False, False)
if role in PERMS:
self.reads[SELF]["permissions"].append(PERMS[role])
self.reads["/stats.self_input/mediaSourceOptions"] = [{"name": SOURCE, "value": "native"}]
self.reads["/dept.dept/all"] = [{"id": 42, "name": "离线部门", "children": []}]
self.hold = {"today"} if role == "reader" else set()
self.pending, self.queries = {}, []
self.large_amount, self.fail_next = False, False
def route(self, route):
req, url = route.request, urlsplit(route.request.url)
if (f"{url.scheme}://{url.netloc}", url.path, req.method) != (OFFICIAL, "/adminapi" + OVERVIEW, "GET"):
return super().route(route)
if req.headers.get("token") != TOKEN:
self.errors.append("overview without fixture session")
return route.abort()
self.calls.append(["GET", OVERVIEW])
query = {k: v[0] for k, v in parse_qs(url.query).items()}
self.queries.append(query)
period = query.get("time_type")
if period not in {"today", "week", "month", "yesterday", "custom"}:
self.errors.append("unexpected stats range")
return route.abort()
if period in self.hold:
self.hold.remove(period)
self.pending[period] = (route, query)
else:
self.respond(route, query)
def release(self, period):
self.respond(*self.pending.pop(period))
def respond(self, route, query):
period = query["time_type"]
if self.fail_next:
self.fail_next = False
return route.fulfill(headers={"Access-Control-Allow-Origin": self.base}, json={
"code": 0, "show": 0, "msg": "离线查询失败", "data": None})
n, date = {"today": (17, "2026-01-30"), "week": (31, "2026-01-24"),
"month": (87, "2026-01-01"), "yesterday": (0, "2026-01-29"),
"custom": (5, query.get("start_date", ""))}[period]
fields = {"add_fans_count": n, "total_open_count": 0, "order_amount": 12.50,
"paid_appointment_count": None, "total_open_rate": 0}
if self.large_amount:
fields["order_amount"] = 12345678901234.50
finance = period == "week"
if finance:
fields.update(account_cost=321.25, roi=1.5, cash_cost=0)
empty = period == "yesterday"
label = "ROW-" + period + ("-filtered" if "media_source" in query else "")
row = dict(fields, id=1, media_source=label, yeji_date=date, creator_name="离线录入员")
data = {"lists": [] if empty else [row], "count": 0 if empty else 1,
"extend": {"date_range": [date, date if empty else "2026-01-30"], "summary": fields,
"can_view_finance": finance}}
route.fulfill(headers={"Access-Control-Allow-Origin": self.base, "Cache-Control": "no-store"},
json={"code": 1, "show": 0, "msg": "", "data": data})
def check(report, name, result, actual):
report["checks"][name] = {"ok": bool(result), "actual": actual}
def shot(page, out, name):
if out:
page.screenshot(path=str(out / f"stats-{name}.png"), animations="disabled")
def card(stats, label):
return stats.locator(".stats-kpi-card").filter(has=stats.page.get_by_text(label, exact=True))
def value(stats, label):
return card(stats, label).locator(".stats-kpi-value").inner_text().strip()
def row_visible(stats, period):
expect(stats.locator(".el-table__body").get_by_text("ROW-" + period, exact=True)).to_be_visible()
def row_value(stats, label):
# Element's column id is shared by the header and the body, even with sticky columns.
return stats.locator(".el-table").evaluate("""(table, name) => {
const th = [...table.querySelectorAll('thead th')].find(h => h.innerText.trim() === name);
const id = th && [...th.classList].find(n => /_column_/.test(n));
return id ? table.querySelector('tbody td.' + id)?.textContent.trim() : null;
}""", label)
def luminance(rgb):
channels = [v / 255 for v in rgb[:3]]
linear = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4 for v in channels]
return sum(v * w for v, w in zip(linear, (.2126, .7152, .0722)))
def palette(stats):
target = card(stats, "加粉数")
# Sample actual rendered pixels, not just backgroundColor (the baseline paints a gradient).
im = Image.open(io.BytesIO(target.screenshot(animations="disabled"))).convert("RGB")
background = im.getpixel((im.width * 3 // 4, im.height // 2))
colors = target.evaluate("""el => ['.stats-kpi-label','.stats-kpi-value'].map(s => {
const c = document.createElement('canvas').getContext('2d');
c.fillStyle = getComputedStyle(el.querySelector(s)).color; c.fillRect(0,0,1,1);
return [...c.getImageData(0,0,1,1).data];
})""")
bg = luminance(background)
ratios = []
for rgb in colors:
alpha = rgb[3] / 255
fg = luminance([v * alpha + b * (1 - alpha) for v, b in zip(rgb, background)])
ratios.append(round((max(fg, bg) + .05) / (min(fg, bg) + .05), 2))
return {"rgb": background, "luminance": round(bg, 3), "label_contrast": ratios[0], "value_contrast": ratios[1]}
def mobile_geometry(stats):
return stats.evaluate("""root => {
const visible = e => e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden';
const w = document.documentElement.clientWidth, rect = e => e.getBoundingClientRect();
const elements = [...root.querySelectorAll('.stats-filter-form .el-radio-button,.stats-filter-form .el-select,' +
'.stats-filter-form .el-button,.stats-kpi-card,.stats-detail-card,.el-pagination button,' +
'.el-pagination .number,.el-pagination .el-select,.el-pagination .el-input')].filter(visible);
const clipped = elements.filter(e => rect(e).x < -1 || rect(e).right > w + 1)
.map(e => [e.textContent.trim().slice(0,20) || e.className, Math.round(rect(e).x),Math.round(rect(e).right)]);
const table = root.querySelector('.el-table__body-wrapper .el-scrollbar__wrap');
const cards = [...root.querySelectorAll('.stats-kpi-card')].filter(visible).map(rect);
const firstRow = cards.filter(r => Math.abs(r.top - cards[0].top) < 2);
const overlap = firstRow.some((r,i) => i && r.left < firstRow[i - 1].right - 1);
return {width:w,clipped,rootWidth:root.clientWidth,contentWidth:root.scrollWidth,
cardsPerRow:firstRow.length,cardWidth:Math.round(firstRow[0]?.width || 0),overlap,
detailOffset:Math.round(rect(root.querySelector('.stats-detail-card')).top - rect(root).top),
tableWidth:table.clientWidth,tableContentWidth:table.scrollWidth};
}""")
def wait_query(page, fixture, *, query_count=None, pending=None):
# Pump browser events while a routed request is deliberately left unanswered.
for _ in range(100):
if ((query_count is None or len(fixture.queries) >= query_count) and
(pending is None or pending in fixture.pending)):
return
page.wait_for_timeout(30)
raise AssertionError(f"missing fixture query: pending={pending}, queries={fixture.queries}")
def enter(page, fixture):
page.goto(fixture.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2")
desktop_entry(page, "自录转化统计").click()
stats = page.locator(PAGE)
expect(stats).to_be_visible()
return stats
def permission_checks(stats, role, report):
table = stats.locator(".el-table")
actions = {
"column": table.locator("thead th").get_by_text("操作", exact=True).count(),
"edit": table.get_by_role("button", name="编辑", exact=True).count(),
"delete": table.get_by_role("button", name="删除", exact=True).count(),
}
wanted = {"column": int(role != "reader"), "edit": int(role == "edit"), "delete": int(role == "delete")}
check(report, f"permissions_{role}", actions == wanted, actions)
def reader_checks(page, stats, fx, report, out):
wait_query(page, fx, pending="today")
loading = card(stats, "加粉数")
val = loading.locator(".stats-kpi-value").inner_text().strip() if loading.locator(".stats-kpi-value").count() else ""
busy = stats.locator("[aria-busy=true]:visible,.el-skeleton:visible,.el-loading-mask:visible,[role=progressbar]:visible").count()
loading_text = bool(re.search(r"加载|读取|统计中", stats.inner_text()))
check(report, "initial_loading_not_zero", not re.search(r"\d", val) and (busy or loading_text),
{"value": val, "busy": busy, "loading_text": loading_text})
shot(page, out, "loading")
fx.release("today")
row_visible(stats, "today")
permission_checks(stats, "reader", report)
values = {k: value(stats, k) for k in ("加粉数", "总开口", "未回复", "付费挂号", "订单金额", "总开口率")}
cells = {k: row_value(stats, k) for k in ("总开口", "未回复", "付费挂号")}
check(report, "known_values_and_real_zero",
[values[k] for k in ("加粉数", "总开口", "总开口率")] == ["17", "0", "0.00%"] and
values["订单金额"] in {"¥12.50", "¥12.50"} and cells["总开口"] == "0", values)
check(report, "missing_and_null_not_zero", all(EMPTY.fullmatch(v or "") for v in
(values["未回复"], values["付费挂号"], cells["未回复"], cells["付费挂号"])), cells)
light = palette(stats)
check(report, "light_cards", light["luminance"] > .5 and min(light["label_contrast"], light["value_contrast"]) >= 4.5, light)
shot(page, out, "light")
page.emulate_media(color_scheme="dark")
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
dark = palette(stats)
check(report, "dark_cards", dark["luminance"] < .2 and min(dark["label_contrast"], dark["value_contrast"]) >= 4.5, dark)
shot(page, out, "dark")
# First a normal finance-enabled result. Then the same period is delayed and must lose to month.
stats.get_by_text("最近7天", exact=True).click()
row_visible(stats, "week")
check(report, "finance_granted", card(stats, "账户消耗").count() == 1 and value(stats, "ROI") == "1.50"
and row_value(stats, "账户消耗") in {"¥321.25", "¥321.25"},
{"finance_cards": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗")})
stats.get_by_text("今天", exact=True).click()
row_visible(stats, "today")
fx.hold.add("week")
stats.get_by_text("最近7天", exact=True).click()
wait_query(page, fx, pending="week")
stats.get_by_text("最近30天", exact=True).click()
row_visible(stats, "month")
# Observe completion of the *older* reply before checking that it did not replace the latest results.
with page.expect_event("requestfinished", predicate=lambda r:
urlsplit(r.url).path == "/adminapi" + OVERVIEW and parse_qs(urlsplit(r.url).query).get("time_type") == ["week"]):
fx.release("week")
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
race = {"value": value(stats, "加粉数"), "month": stats.get_by_text("ROW-month", exact=True).count(),
"finance_card": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗"),
"range": stats.locator(".stats-detail-card .el-card__header").inner_text()}
check(report, "latest_response_wins", race["value"] == "87" and race["month"] == 1 and
race["finance_card"] == 0 and race["finance_column"] is None and "2026-01-01" in race["range"], race)
filters = stats.locator(".stats-filter-form")
filters.locator(".el-form-item").filter(has_text="部门").locator(".el-select__wrapper").click()
page.get_by_role("treeitem").get_by_text("离线部门", exact=True).click()
filters.locator(".el-form-item").filter(has_text="自媒体来源").locator(".el-select__wrapper").click()
page.get_by_role("option", name=SOURCE, exact=True).click()
row_visible(stats, "month-filtered")
query = fx.queries[-1]
check(report, "filters_keep_real_parameters", all(query.get(k) == v for k, v in
{"time_type":"month", "dept_id":"42", "media_source":SOURCE, "page_no":"1", "page_size":"15"}.items()), query)
filters.get_by_role("button", name="重置").click()
row_visible(stats, "today")
query = fx.queries[-1]
check(report, "reset_actual_query", query.get("time_type") == "today" and not query.get("media_source")
and not query.get("dept_id") and query.get("page_no") == "1", query)
page.set_viewport_size({"width":390, "height":844})
expect(page.locator(".app-aside .side")).to_be_hidden()
dimensions = mobile_geometry(stats)
check(report, "390px_two_column_cards", dimensions["cardsPerRow"] == 2, dimensions)
check(report, "390px_controls_and_local_table_scroll", not dimensions["clipped"] and not dimensions["overlap"] and
dimensions["contentWidth"] <= dimensions["rootWidth"] + 1 and
dimensions["tableContentWidth"] > dimensions["tableWidth"] > 0, dimensions)
shot(page, out, "mobile")
fx.large_amount = True
filters.get_by_role("button", name="查询", exact=True).click()
amount = card(stats, "订单金额").locator(".stats-kpi-value")
expect(amount).to_have_text(re.compile(r"12345678901234\.50"))
box = amount.evaluate("""el => {
const r = document.createRange(); r.selectNodeContents(el);
const card = el.closest('.stats-kpi-card').getBoundingClientRect();
const fragments = [...r.getClientRects()].filter(r => r.width && r.height);
return {count: fragments.length, fits: fragments.every(r =>
r.left >= card.left && r.right <= card.right && r.bottom <= card.bottom)};
}""")
check(report, "390px_full_amount_fits", box["count"] and box["fits"], box)
fx.large_amount = False
fx.fail_next = True
filters.get_by_text("最近7天", exact=True).click()
expect(stats.locator(".el-table__body tbody tr")).to_have_count(0)
expect(stats.get_by_role("alert")).to_be_visible()
expect(filters.get_by_role("button", name="查询", exact=True)).to_be_enabled()
stale = value(stats, "加粉数")
check(report, "failed_query_clears_stale_results", EMPTY.fullmatch(stale or ""), stale)
filters.get_by_role("button", name="查询", exact=True).click()
row_visible(stats, "week")
check(report, "retry_succeeds", value(stats, "加粉数") == "31", value(stats, "加粉数"))
filters.get_by_text("昨天", exact=True).click()
expect(stats.locator(".el-table__body tbody tr")).to_have_count(0)
expect(card(stats, "加粉数").locator(".stats-kpi-value")).to_have_text("0")
empty_state = stats.locator(".el-table__empty-text").inner_text().strip()
check(report, "empty_result_has_true_zero", bool(empty_state) and value(stats, "加粉数") == "0", empty_state)
# An incomplete custom range must not replay the preceding period's totals.
n = len(fx.queries)
filters.get_by_text("自定义", exact=True).click()
submit = filters.get_by_role("button", name="查询", exact=True)
expect(submit).to_be_disabled()
check(report, "incomplete_custom_range", n == len(fx.queries) and
EMPTY.fullmatch(value(stats, "加粉数")), {"queries":len(fx.queries)-n})
filters.get_by_placeholder("开始日期").click()
dates = page.locator(".el-date-range-picker__content.is-left:visible td.available")
dates.nth(2).click()
dates.nth(4).click()
row_visible(stats, "custom")
query = fx.queries[-1]
check(report, "custom_range_actual_dates", query.get("time_type") == "custom" and
re.fullmatch(r"\d{4}-\d\d-\d\d", query.get("start_date","")) and
query["start_date"] < query.get("end_date",""), query)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--out", type=Path, help="Write JSON and local screenshots to this directory")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
report = {"checks": {}, "infrastructure_errors": []}
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
for role in ("reader", "edit", "delete"):
fixture = StatsFixture(args.host, role)
with browser.new_context(service_workers="block", viewport={"width":1440,"height":960}, color_scheme="light") as ctx:
ctx.set_default_timeout(6000)
ctx.route("**/*", fixture.route)
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
page = ctx.new_page()
page.on("pageerror", lambda err: fixture.errors.append(str(err)))
try:
stats = enter(page, fixture)
if role == "reader":
reader_checks(page, stats, fixture, report, args.out)
else:
row_visible(stats, "today")
permission_checks(stats, role, report)
assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN]
except Exception as e:
report["infrastructure_errors"].append({"role": role, "error": str(e)})
shot(page, args.out, f"failure-{role}")
report["infrastructure_errors"].extend(fixture.errors)
report["status"] = ("PASS" if report["checks"] and all(c["ok"] for c in report["checks"].values())
and not report["infrastructure_errors"] else "FAIL")
report["real_api_calls"] = 0
if args.out:
(args.out / "stats-visual.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)+"\n")
print(json.dumps(report, ensure_ascii=False))
return int(report["status"] != "PASS")
if __name__ == "__main__":
raise SystemExit(main())
+180
View File
@@ -0,0 +1,180 @@
"""Offline Playwright contract for the real native work tabs (never contacts the official API)."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, COST, LOGIN, OVERVIEW, PASS, SELF, USER, Fixture, desktop_entry, loopback, menu
HOME = "自录转化统计"
LONG = "账户消耗录入与跨部门合作经营分析报表历史记录逐日统计明细汇总工作清单"
THIRD = "渠道复核"
TOOLS = "标签页操作"
def register_menu(fixture):
leaves = fixture.reads[SELF]["menu"][0]["children"][0]["children"]
leaves[1]["name"] = LONG
leaves.append(menu(305, THIRD, "review?via=tabs&team=qa", component="stats/self_input/index"))
def geometry(tab):
return tab.evaluate("""async el => {
const next = () => new Promise(r => requestAnimationFrame(r));
await next(); await next();
const strip = el.closest('.app-tabs');
await Promise.allSettled(strip.getAnimations({subtree:true})
.filter(a => a.effect?.getComputedTiming().endTime < Infinity).map(a => a.finished));
const r = el.getBoundingClientRect(), clip = strip.querySelector('.el-tabs__nav-scroll').getBoundingClientRect();
const x = el.querySelector('.is-icon-close'), c = x.getBoundingClientRect();
const hit = (node,rect) => node.contains(document.elementFromPoint(rect.x+rect.width/2, rect.y+rect.height/2));
const label = [...el.querySelectorAll('*')].find(n => n.innerText === el.innerText &&
getComputedStyle(n).textOverflow === 'ellipsis' && n.scrollWidth > n.clientWidth);
return {tabWidth:r.width, stripWidth:clip.width, inside: r.left >= clip.left-1 && r.right <= clip.right+1,
hitLabel: hit(el,r), hitClose: c.width > 0 && hit(x,c), ellipsis: !!label,
overlap: label ? label.getBoundingClientRect().right > c.left+1 : null,
title: el.title || [...el.querySelectorAll('[title]')].find(n=>n.title)?.title || '',
namedActions: !!strip.querySelector('button[aria-label="标签页操作"]')};
}""")
def shot(page, out, name):
if out:
page.screenshot(path=str(out / f"tabs-{name}.png"), animations="disabled")
def exercise(page, fixture, out):
page.goto(fixture.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
strip = page.locator(".app-tabs")
tabs = strip.get_by_role("tab")
actions = strip.get_by_role("button", name=TOOLS, exact=True)
tab = lambda name: strip.get_by_role("tab", name=name, exact=True)
cmd = lambda name: page.get_by_role("menuitem", name=name, exact=True)
def visit(name):
desktop_entry(page, name).click()
active(name)
def active(name):
expect(tab(name)).to_have_attribute("aria-selected", "true")
path, query, component = {
HOME: ("/admin/stats/self_input", {}, "self-input-stats-page"),
LONG: ("/admin/stats/self_input/account_cost", {"via": ["sidebar"]}, "personal-account-cost-page"),
THIRD: ("/admin/stats/self_input/review", {"via": ["tabs"], "team": ["qa"]}, "self-input-stats-page"),
}[name]
expect(page).to_have_url(re.compile(re.escape(path) + r"/?(?:\?.*)?$"))
assert parse_qs(urlsplit(page.url).query) == query, ("route query", name)
expect(page.locator("main ." + component)).to_be_visible()
expect(strip.locator('[role=tab][aria-selected="true"]')).to_have_count(1)
visit(HOME)
visit(LONG)
visit(THIRD)
expect(tabs).to_have_count(3)
tab(LONG).click()
active(LONG)
# An inactive close icon must remove *that* tab without first navigating to it.
tab(THIRD).locator(".is-icon-close").click()
expect(tabs).to_have_count(2)
active(LONG)
visit(THIRD)
# A user may follow an in-page bookmark; switching tabs must not drop it.
page.evaluate("location.hash = 'details'")
expect(tab(THIRD)).to_have_attribute("id", re.compile(r"#details$"))
tab(HOME).click()
active(HOME)
page.emulate_media(color_scheme="dark")
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
page.set_viewport_size({"width": 390, "height": 844})
tab(HOME).focus()
page.keyboard.press("ArrowRight")
active(LONG)
metrics = geometry(tab(LONG))
# ElTabs schedules scrollToActiveTab after the route update and resize
# observer. Poll the painted hit targets, rather than assume two frames.
for _ in range(25):
if metrics["inside"] and metrics["hitClose"]:
break
page.wait_for_timeout(40)
metrics = geometry(tab(LONG))
print("dark 390px:", json.dumps(metrics, ensure_ascii=False), flush=True)
shot(page, out, "dark-390")
assert metrics["inside"] and metrics["hitClose"] and metrics["hitLabel"], metrics
assert metrics["ellipsis"] and not metrics["overlap"], metrics
if metrics["title"] != LONG:
tab(LONG).hover()
expect(page.get_by_role("tooltip").get_by_text(LONG, exact=True)).to_be_visible()
expect(actions).to_be_visible()
tab(LONG).focus()
page.keyboard.press("Tab")
expect(actions).to_be_focused()
page.keyboard.press("Enter")
expect(cmd("关闭当前")).to_be_visible()
page.keyboard.press("Escape")
expect(cmd("关闭当前")).to_be_hidden()
expect(actions).to_be_focused()
actions.press("Enter")
cmd("关闭当前").click()
expect(tabs).to_have_count(2)
expect(tab(LONG)).to_have_count(0)
active(HOME)
# Route & query of the retained tab must survive both the switch and bulk close.
tab(THIRD).click()
active(THIRD)
assert urlsplit(page.url).fragment == "details", page.url
actions.click()
cmd("关闭其他").click()
expect(tabs).to_have_count(1)
active(THIRD)
expect(tab(THIRD).locator(".is-icon-close")).to_have_count(0)
actions.press("Enter")
expect(cmd("关闭当前")).to_be_disabled()
expect(cmd("关闭其他")).to_be_disabled()
shot(page, out, "single")
page.keyboard.press("Escape")
expect(cmd("关闭其他")).to_be_hidden()
return metrics
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--out", type=Path, help="Optional directory for local screenshots")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
fixture = Fixture(args.host, False, False)
register_menu(fixture)
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
with browser.new_context(service_workers="block", viewport={"width": 1440, "height": 960},
color_scheme="light") as ctx:
ctx.set_default_timeout(8000)
ctx.route("**/*", fixture.route)
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
ctx.on("page", lambda p: p.on("pageerror", lambda e: fixture.errors.append(str(e))))
page = ctx.new_page()
try:
metrics = exercise(page, fixture, args.out)
assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN], fixture.calls
assert not fixture.errors, fixture.errors
except Exception:
shot(page, args.out, "failure")
print("mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
raise
print(json.dumps({"work_tabs": "PASS", "real_api_calls": 0, "dark390": metrics}, ensure_ascii=False))
if __name__ == "__main__":
main()
@@ -0,0 +1,176 @@
"""Headless native workbench feedback. Only loopback static files may reach the network."""
import argparse
import json
import time
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, PASS, SELF, TOKEN, Fixture, loopback, menu
ORDER = "/order.order/orderStats"
DIAG = "/tcm.diagnosis/assistantDiagnosisStats"
TREND = "/workbench/index"
class WorkbenchFixture(Fixture):
def __init__(self, host):
super().__init__(host, False, False)
self.reads[SELF]["menu"] = [menu(911, "工作台", "workbench", component="workbench/index", perm="workbench/index")]
self.reads[SELF]["permissions"] = [ORDER[1:], DIAG[1:], TREND[1:]]
self.pending = {}
def route(self, route):
req, url = route.request, urlsplit(route.request.url)
path = url.path.removeprefix("/adminapi")
if f"{url.scheme}://{url.netloc}" != OFFICIAL or not url.path.startswith("/adminapi/") or path not in (ORDER, DIAG, TREND) or req.method != "GET":
return super().route(route)
q = parse_qs(url.query)
if req.headers.get("token") != TOKEN or set(q) != {ORDER: {"order_type", "days"}, DIAG: {"days"}, TREND: set()}[path]:
self.errors.append("unexpected workbench query or missing fixture session")
return route.abort()
if path == ORDER and q["order_type"] != ["-1"]:
self.errors.append("unexpected order type")
return route.abort()
key = (path, q.get("days", [""])[0])
if key in self.pending:
self.errors.append("duplicate pending workbench request")
return route.abort()
self.pending[key] = route
self.calls.append(["GET", path])
def release(self, page, key, data=None, *, failure=False):
until = time.monotonic() + 5
while key not in self.pending and time.monotonic() < until:
page.wait_for_timeout(15)
assert key in self.pending, (key, self.calls)
route = self.pending.pop(key)
with page.expect_event("requestfinished", predicate=lambda req: req == route.request):
route.fulfill(headers={"Access-Control-Allow-Origin": self.base}, json={
"code": 0 if failure else 1, "show": 0, "msg": "离线验收" if failure else "", "data": data})
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
def orders(count, amount, name="全部已支付"):
return {"today_total": count, "today_amount": amount, "order_type_name": name,
"date_range": ["2026-01-01", "2026-01-07"], "today_ranking": [], "departments": [], "ranking": [],
"chart": {"xAxis": [], "series": []}}
def series(values):
return {"date": ["01/02", "01/01"], "list": [{"data": values}]}
def run(browser, args, mobile):
fixture = WorkbenchFixture(args.host)
mode = "dark" if mobile else "light"
size = {"width": 390, "height": 844} if mobile else {"width": 1440, "height": 960}
with browser.new_context(service_workers="block", color_scheme=mode, viewport=size, reduced_motion="reduce") as ctx:
ctx.set_default_timeout(8000)
ctx.route("**/*", fixture.route)
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
page = ctx.new_page()
page.on("pageerror", lambda err: fixture.errors.append(str(err)))
page.goto(fixture.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
page.wait_for_url("**/admin/workbench", timeout=15000)
order, diag, trend = [page.locator(".wb-section--" + name) for name in ("order", "diagnosis", "trend")]
for section in (order, diag):
expect(section).to_have_attribute("data-state", "loading")
expect(section.get_by_role("status")).to_contain_text("正在读取")
expect(section.locator(".wb-kpi-value, canvas, .el-empty")).to_have_count(0)
expect(trend).to_have_attribute("data-state", "collapsed")
opener = trend.get_by_role("button", name="查看示例趋势")
expect(opener).to_have_attribute("aria-expanded", "false")
expect(trend.locator("canvas, .wb-placeholders")).to_have_count(0)
assert ["GET", TREND] not in fixture.calls
assert order.locator(".wb-placeholders i").first.evaluate("e => getComputedStyle(e).animationName") == "none"
assert page.locator("html").evaluate("e => e.classList.contains('dark')") == mobile
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth + 1")
if args.out:
order.scroll_into_view_if_needed()
page.screenshot(path=str(args.out / f"workbench-{mode}-loading.png"))
# Independent completions: genuine zero, an isolated failure, two explicitly empty plots.
fixture.release(page, (ORDER, "0"), orders(0, "0.00"))
fixture.release(page, (DIAG, "0"), failure=True)
assert ["GET", TREND] not in fixture.calls
opener.click()
expect(trend.get_by_role("button", name="收起示例趋势")).to_have_attribute("aria-expanded", "true")
expect(trend).to_have_attribute("data-state", "loading")
fixture.release(page, (TREND, ""), {"visitor": series([]), "sale": series([None, None])})
expect(order.locator(".wb-kpi-value")).to_have_text(["0", "¥0.00"])
expect(diag.get_by_role("status")).to_contain_text("读取失败")
expect(trend.get_by_text("暂无销售额趋势数据")).to_be_visible()
expect(trend.locator("canvas")).to_have_count(0)
if args.out:
diag.scroll_into_view_if_needed()
page.screenshot(path=str(args.out / f"workbench-{mode}-error.png"))
before = len(fixture.calls)
diag.get_by_role("button", name="重试诊单统计").click()
expect(diag).to_have_attribute("data-state", "loading")
fixture.release(page, (DIAG, "0"), {"today_total": 13, "date_range": ["01/01", "01/02"]})
expect(diag.locator(".wb-kpi-value")).to_have_text("13")
assert [p for _, p in fixture.calls[before:] if p in (ORDER, DIAG, TREND)] == [DIAG]
# Switch two filters rapidly: older success may not overwrite the current response.
for label in ("最近7天", "最近30天"):
order.locator(".el-select").nth(1).click()
page.get_by_role("option", name=label, exact=True).click()
expect(order).to_have_attribute("data-state", "loading")
expect(order.locator(".wb-kpi-value")).to_have_count(0)
fixture.release(page, (ORDER, "30"), orders(32, None, "当前筛选"))
fixture.release(page, (ORDER, "7"), orders(7, "888.00", "过期结果"))
expect(order.locator(".wb-kpi-value")).to_have_text(["32", "—"])
expect(order).not_to_contain_text("过期结果")
expect(diag.locator(".wb-kpi-value")).to_have_text("13")
page.get_by_role("button", name="刷新全部").click()
for section in (order, diag, trend):
expect(section).to_have_attribute("data-state", "loading")
fixture.release(page, (ORDER, "30"), failure=True)
fixture.release(page, (DIAG, "0"), {"today_total": 0})
fixture.release(page, (TREND, ""), failure=True)
expect(diag.locator(".wb-kpi-value")).to_have_text("0")
order.get_by_role("button", name="重试订单统计").click()
fixture.release(page, (ORDER, "30"), orders(26, "416.80"))
expect(order.locator(".wb-kpi-value")).to_have_text(["26", "¥416.80"])
trend.get_by_role("button", name="重试运营趋势").click()
fixture.release(page, (TREND, ""), {"visitor": series([0, 2]), "sale": series([8, 66])})
expect(trend.locator("canvas")).to_have_count(2)
if args.out:
trend.scroll_into_view_if_needed()
page.screenshot(path=str(args.out / f"workbench-{mode}-ready.png"))
trend.get_by_role("button", name="收起示例趋势").click()
expect(trend).to_have_attribute("data-state", "collapsed")
expect(trend.locator("canvas")).to_have_count(0)
count = fixture.calls.count(["GET", TREND])
page.get_by_role("button", name="刷新全部").click()
fixture.release(page, (ORDER, "30"), orders(12, "22.00"))
fixture.release(page, (DIAG, "0"), {"today_total": 4})
expect(order.locator(".wb-kpi-value")).to_have_text(["12", "¥22.00"])
expect(diag.locator(".wb-kpi-value")).to_have_text("4")
expect(opener).to_have_attribute("aria-expanded", "false")
assert fixture.calls.count(["GET", TREND]) == count
assert not fixture.pending and not fixture.errors, (fixture.errors, list(fixture.pending))
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN]
return {"mode": mode, "width": size["width"], "workbench_reads": sum(path in (ORDER, DIAG, TREND) for _, path in fixture.calls)}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--out", type=Path)
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
cases = [run(browser, args, mobile) for mobile in (False, True)]
print(json.dumps({"workbench_feedback": "PASS", "real_api_calls": 0, "cases": cases}, ensure_ascii=False))
+15
View File
@@ -0,0 +1,15 @@
// Build the actual admin entry/router/permission store, not a projected preview.
// Output remains in the worktree; do not run scripts/release.mjs.
import {build} from 'vite'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
const here=path.dirname(fileURLToPath(import.meta.url)), root=path.dirname(here)
process.chdir(root)
const name=process.argv[2]
if(name && !/^[a-z][a-z0-9-]{1,48}$/.test(name))throw Error('Use a short lowercase candidate name')
const target=path.join(root,'node_modules/.zyt-live-native',...(name?['candidates',name]:['dist']))
await build({root,mode:'live-native',configFile:path.join(root,'vite.config.ts'),envFile:false,
define:{'import.meta.env.VITE_APP_BASE_URL':JSON.stringify('https://admin.zhenyangtang.com.cn')},
cacheDir:path.join(root,'node_modules/.zyt-live-native/cache'),
build:{outDir:target,emptyOutDir:true,sourcemap:false,reportCompressedSize:false,
rollupOptions:{input:path.join(here,'index.html')}}})
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="zh-CN" data-default-admin-ui="v2">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="referrer" content="no-referrer" />
<title>甄养堂管理后台</title>
<link rel="icon" href="data:," />
<link rel="stylesheet" href="/admin-loading.css" />
<script defer src="/admin-boot.js"></script>
</head>
<body>
<div id="admin-boot" data-state="loading">
<div>
<svg class="boot-mark" width="40" height="40" viewBox="0 0 40 40" fill="currentColor" aria-hidden="true">
<circle cx="20" cy="8" r="4"/><circle cx="32" cy="20" r="4" opacity=".76"/>
<circle cx="20" cy="32" r="4" opacity=".52"/><circle cx="8" cy="20" r="4" opacity=".32"/>
</svg>
<strong>甄养堂管理后台</strong>
<p role="status" aria-atomic="true">
<span data-message="loading">正在打开工作台…</span>
<span data-message="slow">加载时间较长,可继续等待或重新加载。</span>
<span data-message="error">工作台未能打开,请检查网络后重试。</span>
</p>
<a id="admin-boot-retry" href="">重新加载</a>
<noscript>请启用 JavaScript 后重新加载。</noscript>
</div>
</div>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
// Publish a tested static build to the *loopback* service. Retain older hashed
// chunks for already-open tabs; atomically change HTML only after all copies finish.
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {copyFile, mkdir, readFile, readdir, rename, writeFile} from 'node:fs/promises'
import {randomUUID} from 'node:crypto'
const root=fileURLToPath(new URL('../node_modules/.zyt-live-native/',import.meta.url))
const [action,name]=process.argv.slice(2)
if(!['apply','restore'].includes(action)||!/^[a-z][a-z0-9-]{1,48}$/.test(name??'')) throw Error('Usage: promote-local.mjs apply|restore <candidate>')
const candidate=path.join(root,'candidates',name), live=path.join(root,'dist'), entry='live-native/index.html', old=path.join(root,'checkpoints',name+'.html')
async function atomic(dst,bytes){const temp=dst+'.'+randomUUID()+'.tmp';await writeFile(temp,bytes);await rename(temp,dst)}
async function sync(dir,relative=''){
for (const item of await readdir(dir,{withFileTypes:true})){
const rel=path.join(relative,item.name),dst=path.join(live,rel)
if(item.isDirectory()){await mkdir(dst,{recursive:true});await sync(path.join(dir,item.name),rel)}
else if(item.isFile() && rel!==entry){const temp=dst+'.'+randomUUID()+'.tmp';await copyFile(path.join(dir,item.name),temp);await rename(temp,dst)}
}
}
const next=await readFile(path.join(candidate,entry),'utf8');const assets=[...next.matchAll(/(?:src|href)="\/admin\/(assets\/[^"?]+)"/g)].map(m=>m[1]);if(!assets.length)throw Error('No build assets referenced')
if(action==='apply'){
for(const a of assets) await readFile(path.join(candidate,a))
await mkdir(path.dirname(old),{recursive:true});await writeFile(old,await readFile(path.join(live,entry)),{flag:'wx'})
await sync(candidate);await atomic(path.join(live,entry),next)
}else{
if(await readFile(path.join(live,entry),'utf8')!==next)throw Error('The active version changed; refusing to overwrite it')
await atomic(path.join(live,entry),await readFile(old));
}
console.log(`local ${action}: ${name}`)
+32
View File
@@ -0,0 +1,32 @@
// Loopback static site for the native browser application; never forward logins, tokens or business APIs.
import http from 'node:http'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {readFile} from 'node:fs/promises'
const host='127.0.0.1',port=process.argv[2]==='--qa'?5181:5179,self=`http://${host}:${port}`,official='https://admin.zhenyangtang.com.cn'
const candidate=port===5181 ? process.argv[3] : undefined
if(candidate && !/^[a-z][a-z0-9-]{1,48}$/.test(candidate))throw Error('Invalid candidate')
const base=fileURLToPath(new URL('../node_modules/.zyt-live-native/',import.meta.url))
const dist=candidate?path.join(base,'candidates',candidate):path.join(base,'dist'),entry=path.join(dist,'live-native/index.html')
const types={js:'text/javascript',css:'text/css',svg:'image/svg+xml',png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp',gif:'image/gif',ico:'image/x-icon',woff:'font/woff',woff2:'font/woff2',ttf:'font/ttf',otf:'font/otf',mp3:'audio/mpeg',mp4:'video/mp4',json:'application/json',wasm:'application/wasm'}
// Same-origin program assets. API authorization, including write permissions, belongs to the official backend.
// Media may be served by the storage provider configured by the business; never proxy it through localhost.
const csp=`default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' https://web.sdk.qcloud.com; connect-src 'self' ${official} https://*.myqcloud.com https://*.aliyuncs.com https://*.tencentcloudapi.com https://*.rtc.qq.com https://*.my-imcloud.com wss://*.rtc.qq.com wss://*.my-imcloud.com; img-src 'self' https: data: blob:; font-src 'self' data:; media-src 'self' https: blob:; frame-src 'self' ${official} https://*.zhenyangtang.com.cn https://open.work.weixin.qq.com; form-action 'self' ${official}; frame-ancestors 'none'; base-uri 'none'; worker-src 'self' blob:; object-src 'none'`
await readFile(entry)
http.createServer(async(req,res)=>{
res.setHeader('Referrer-Policy','no-referrer');res.setHeader('Cache-Control','no-store');res.setHeader('Content-Security-Policy',csp);res.setHeader('X-Content-Type-Options','nosniff')
const send=(s,t,b)=>{res.writeHead(s,{'Content-Type':t});res.end(req.method==='HEAD'?undefined:b)}
if(req.headers.host!==`${host}:${port}` || (req.headers.origin && req.headers.origin!==self))return send(403,'text/plain','Forbidden')
if(!['GET','HEAD'].includes(req.method))return send(405,'text/plain','Static site only')
if(!req.url?.startsWith('/') || req.url.startsWith('//'))return send(400,'text/plain','Invalid path')
try{
const url=new URL(req.url,self),name=decodeURIComponent(url.pathname)
if(name==='/' || name==='/admin' || /^\/admin\/nav\/(?:m-\d+|p-[a-z0-9]+)(?:-\d+)?\/?$/.test(name)){res.writeHead(302,{Location:'/admin/'});return res.end()}
if(!name.startsWith('/admin/') || /[\\\x00-\x1f]/.test(name))return send(404,'text/plain','Not found')
const suffix=name.slice(7),parts=suffix.split('/');if(parts.some(p=>p==='..'||p.startsWith('.')))return send(404,'text/plain','Not found')
const ext=path.extname(name).slice(1).toLowerCase()
if(ext && Object.hasOwn(types,ext))return send(200,types[ext],await readFile(path.join(dist,suffix)))
if(parts[0]==='assets' || /\.(?:map|env|php|ini|sh|pem|log|sql)$/i.test(name))return send(404,'text/plain','Not found')
return send(200,'text/html; charset=utf-8',await readFile(entry))
}catch{return send(404,'text/plain','Not found')}
}).listen(port,host,()=>console.log(`甄养堂管理后台 ${self}/admin/login`))
+74
View File
@@ -0,0 +1,74 @@
<template>
<span class="real-identity"
><b>正式数据 · 只读</b><span>{{ user.userInfo.name }}</span
><button
type="button"
data-refresh-online-menu
:title="`正式账号返回:${user.routes.length} 个一级入口,${Object.keys(user.entries).length} 个可见页面`"
:disabled="user.syncing"
@click="refresh"
>
{{ user.syncing ? '正在同步…' : '刷新线上菜单' }}</button
><el-button link @click="leave">退出预览</el-button></span
>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import useTabsStore from '@/stores/modules/multipleTabs'
import useUserStore from './user'
const user = useUserStore(),
route = useRoute(),
router = useRouter()
function leave() {
user.forget()
location.replace('/admin/login')
}
async function refresh() {
const current = route.name === 'live-menu' ? String(route.params.menuId) : null
try {
await user.syncMenu()
useTabsStore().resetState()
const id = current && user.entries[current] ? current : user.firstId
await router.replace(
id
? {
name: 'live-menu',
params: { menuId: id },
query: user.entries[id].query || {},
force: true
}
: { name: 'live-unavailable', force: true }
)
ElMessage.success('已按正式账号重新加载菜单')
} catch {
await router.replace('/login')
}
}
</script>
<style scoped>
.real-identity {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 12px;
}
.real-identity b,
.real-identity button[data-refresh-online-menu] {
color: var(--el-color-primary);
}
button[data-refresh-online-menu] {
background: none;
border: 0;
cursor: pointer;
font: inherit;
}
@media (max-width: 680px) {
.real-identity > span {
display: none;
}
.real-identity {
gap: 4px;
}
}
</style>
+15
View File
@@ -0,0 +1,15 @@
<template>
<el-result
icon="info"
title="当前没有可打开的菜单"
sub-title="该页面不在你的正式账号菜单内,或本次同步没有返回可见菜单。可以点击右上角「刷新线上菜单」重试。"
><template #extra
><a
href="https://admin.zhenyangtang.com.cn/admin/"
target="_blank"
rel="noopener noreferrer"
>打开正式后台 ↗</a
></template
></el-result
>
</template>
+21
View File
@@ -0,0 +1,21 @@
<template>
<el-breadcrumb class="app-breadcrumb"
><el-breadcrumb-item v-for="(title, i) in titles" :key="i">{{
title
}}</el-breadcrumb-item></el-breadcrumb
>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import useUserStore from './user'
const user = useUserStore(),
route = useRoute()
const titles = computed(() =>
route.name === 'live-menu'
? user.entries[String(route.params.menuId)]?.breadcrumbs || []
: route.meta.title
? [String(route.meta.title)]
: []
)
</script>
+63
View File
@@ -0,0 +1,63 @@
<template>
<component v-if="view && entry" :is="view" :key="`${entry.id}:${user.menuVersion}`" />
<section v-else-if="entry" class="online-entry">
<h1>{{ entry.title }}</h1>
<p>这是正式账号菜单中的入口。此页未接入本地只读查询,未向线上发起业务请求。</p>
<template v-if="entry.officialHref">
<p>
{{
entry.external
? `该菜单指向 ${destinationHost},将单独打开。`
: '在正式后台打开后,将使用正式站点的原有权限,可能需要单独登录。'
}}
</p>
<a
:href="entry.officialHref"
target="_blank"
rel="noopener noreferrer"
referrerpolicy="no-referrer"
>{{ entry.external ? '打开菜单指定站点' : '在正式后台打开' }} ↗</a
>
</template>
<p v-else>未提供可直接打开的页面地址。</p>
</section>
</template>
<script setup lang="ts">
import { computed, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import { screens } from './screens'
import useUserStore from './user'
const route = useRoute(),
user = useUserStore()
const components = new Map(screens.map((s) => [s.key, defineAsyncComponent(s.component)]))
const entry = computed(() => user.entries[String(route.params.menuId)])
const destinationHost = computed(() => entry.value?.officialHref ? new URL(entry.value.officialHref).hostname : '')
const view = computed(() =>
entry.value?.liveKey && user.keys.includes(entry.value.liveKey)
? components.get(entry.value.liveKey)
: null
)
</script>
<style scoped>
.online-entry {
max-width: 800px;
padding: 24px;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-light);
border-radius: 12px;
}
.online-entry h1 {
font-size: 22px;
margin: 0 0 12px;
}
.online-entry p {
color: var(--el-text-color-regular);
margin: 8px 0;
}
.online-entry a {
display: inline-block;
margin-top: 12px;
color: var(--el-color-primary);
text-decoration: underline;
}
</style>
+25
View File
@@ -0,0 +1,25 @@
> 历史模式,已由 [本机完整后台](../live-native/README.md) 取代。当前 5179 不运行此目录的只读壳;以下是早期版本说明。
# 正式数据查询 · 仅本机登录
**入口:<http://127.0.0.1:5179/admin/login>。** 旧书签 5178 只跳转到 5179;合成数据演示只能在显式启动的 5180 访问。5179 使用本分支的真实后台登录表单、布局和业务组件;不包含演示记录、不导入原聚合快照。这里不配置 SQL,也不与本机预览服务交换密码或令牌。用户亲自在浏览器内登录,浏览器直接向 `https://admin.zhenyangtang.com.cn/adminapi/` 发 HTTPS 请求,使用服务器原账号权限。只支持本站原生账号密码;扫码/统一登录、首次改密、强制绑定等在正式站点完成。未授权的页面保持关闭。
`server.mjs` 是只绑定 IPv4 回环的静态 HTTP 服务。它不收登录 POST,也没有后端转发;CSP 只允许所列正式查询/登录路径,不加载外部脚本。不将访问参数、账号、令牌或业务响应写日志。除了正常账号认证的 POST,适配层只允许事先审查的 GET 路径、固定参数和页数。同步账单、导出、调账、修改排班、订单详情(原接口会写查看记录)等均不开放。
「只读」指**不提供业务写操作**,不等于具备数据库级只读账号:正常登录由正式后台管理,会话、登录时间、审计/续期及既有单端登录策略均照常生效。点击右上角「退出预览」或刷新页面会丢弃本页内存令牌;它不是对线上会话的强制注销。请勿向聊天提交账号密码或 token。
在 `admin` 目录运行:
```sh
node live-readonly/build.mjs && node live-readonly/server.mjs
```
验证(不使用真实账号):`node --test live-readonly/resources.test.mjs live-readonly/transport.test.mjs`;`browser_contract.py --out <截图目录>` 使用全新的浏览器,拦截整个正式域名并只返回测试响应。只有正式账号本人登录后,才能确认该账号实际可见的实时数据。
本机运行任务:`launchctl print gui/$(id -u)/local.zyt.live-readonly.bfc2`。退出服务:`launchctl remove local.zyt.live-readonly.bfc2`。未安装开机启动项。
## 左栏的数据来源
登录和「刷新线上菜单」均读取本次账号 `/auth.admin/mySelf` 返回的 `data.menu`。可见目录、层级、同名项、显示名称、图标与顺序由正式服务器决定;隐藏、禁用和按钮权限项不挤进侧栏。已审过的页面使用本地新版只读组件;其余真实菜单保留,点击会说明可否进入正式页面。仅用户再次明确选择才新开正式站或菜单指定的外部站点,不向目标传递本地令牌。正式站沿用其原有登录与操作权限。无返回菜单时不补演示菜单。可运行 `browser_menu_contract.py --help` 查看多层级、同名项及权限变更的离线验收。
浏览器验收仅使用 Playwright 配套的 Chromium Headless Shell,不调用系统 Google Chrome。未安装专用引擎时,跳过浏览器验收;不要指定系统浏览器补跑。
+35
View File
@@ -0,0 +1,35 @@
"""Offline browser contract: the production hostname is intercepted; never send test credentials upstream."""
from argparse import ArgumentParser
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import expect,sync_playwright
import json
p=ArgumentParser();p.add_argument('--out',type=Path,required=True);arg=p.parse_args();arg.out.mkdir(parents=True,exist_ok=True)
base='http://127.0.0.1:5179'; official='https://admin.zhenyangtang.com.cn'; calls=[]; unexpected=[]; errors=[]
with sync_playwright() as pw:
b=pw.chromium.launch(headless=True, args=['--disable-background-networking','--no-proxy-server','--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'])
c=b.new_context(service_workers='block',viewport={'width':1320,'height':850});page=c.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
def route(r):
u=urlsplit(r.request.url); path=u.path.removeprefix('/adminapi');m=r.request.method
if u.scheme=='http' and u.netloc=='127.0.0.1:5179' and m=='GET': return r.continue_()
if u.scheme!='https' or u.netloc!='admin.zhenyangtang.com.cn' or not u.path.startswith('/adminapi/'):
unexpected.append([m,u.path]);return r.abort()
cors={'Access-Control-Allow-Origin':base,'Access-Control-Allow-Methods':'GET,POST,OPTIONS','Access-Control-Allow-Headers':'token,version,content-type,accept','Cache-Control':'no-store'}
if m=='OPTIONS':return r.fulfill(status=204,headers=cors)
calls.append([m,path]);assert r.request.headers.get('cookie') is None
def reply(data):return r.fulfill(headers=cors,json={'code':1,'show':0,'msg':'','data':data})
if (m,path)==('POST','/login/account'):
assert r.request.post_data_json=={'account':'offline-qa','password':'offline-test-only','terminal':1};return reply({'token':'offline-session-example','is_paw':1,'need_bind_work_wechat':False})
assert r.request.headers.get('token')=='offline-session-example'
if (m,path)==('GET','/auth.admin/mySelf'):return reply({'user':{'id':999,'name':'离线验收角色','disable':0,'is_paw':1,'root':0,'need_bind_work_wechat':False},'permissions':['order.order/lists'],'menu':[{'type':'C','paths':'orders','component':'order/index','is_disable':0,'is_show':1,'perms':'order.order/lists'}]})
if (m,path)==('GET','/order.order/lists'):return reply({'lists':[{'id':1,'order_no':'OFFLINE-VIEW-001','order_type':1,'status':2,'payment_time':'2026-12-01','create_time':'2026-12-01','amount':'2.00','is_exempt':0,'creator':{'name':'演示'},'patient':None,'prescription_orders':[]}],'count':1,'extend':{}})
unexpected.append([m,path]);return r.abort()
c.route('**/*',route); page.goto(base+'/admin/order',wait_until='networkidle'); expect(page.get_by_placeholder('请输入账号')).to_be_visible(); assert not calls
page.screenshot(path=str(arg.out/'login.png'))
page.get_by_placeholder('请输入账号').fill('offline-qa');page.get_by_placeholder('请输入密码').fill('offline-test-only');page.get_by_role('button',name='登录',exact=True).click()
expect(page.get_by_text('OFFLINE-VIEW-001',exact=True)).to_be_visible(timeout=10000);expect(page.get_by_text('正式数据 · 只读',exact=True)).to_be_visible(); expect(page.get_by_role('menuitem')).to_have_count(1)
assert not page.get_by_role('button',name='详情',exact=True).count() and not page.get_by_role('button',name='创建支付单').count()
saved=page.evaluate('JSON.stringify([Object.entries(localStorage),Object.entries(sessionStorage),document.cookie])');assert all(x not in saved for x in ['offline-test-only','offline-session-example','offline-qa','OFFLINE-VIEW-001'])
page.get_by_role('button',name='退出预览').click();expect(page.get_by_placeholder('请输入账号')).to_be_visible();page.goto(base+'/admin/order',wait_until='networkidle');expect(page.get_by_placeholder('请输入账号')).to_be_visible();assert not unexpected and not errors,(unexpected,errors)
b.close()
print(json.dumps({'offline_browser_pass':True,'intercepted_paths':calls,'real_auth_requests':0,'unexpected':unexpected,'page_errors':errors},ensure_ascii=False))
@@ -0,0 +1,230 @@
"""Black-box menu contract. Run against the local static build; no real network or account."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
HOST = "admin.zhenyangtang.com.cn"
LOGIN = "/adminapi/login/account"
SELF = "/adminapi/auth.admin/mySelf"
ORDERS = "/adminapi/order.order/lists"
ACCOUNT, PASSWORD, TOKEN = "offline-menu-qa", "offline-only-password", "offline-only-session"
ROW, FILTERED = "OFFLINE-ROW-001", "OFFLINE-MATCH-002"
def node(id_, name, path, children=None, component="", perms="", **flags):
entry = dict(id=id_, name=name, paths=path, type="M" if children is not None else "C",
component=component, perms=perms, is_show=1, is_disable=0)
entry.update(flags)
if children is not None:
entry["children"] = children
return entry
def profile(phase):
first_group = node(91, "收费事务", "payments", [
node(83, "对账事务", "settlement", [
node(72, "处方收款明细", "receipts", component="order/index", perms="order.order/lists"),
node(35, "业务台账", "ledger", component="settle/ledger", perms="settle.ledger/lists"),
node(36, "隐藏的测试入口", "hidden", component="unused/index", is_show=0),
node(37, "停用的测试入口", "disabled", component="unused/index", is_disable=1),
]),
node(18, "阶段汇总", "summary", component="settle/summary", perms="settle.summary/lists"),
node(19, "隐藏的目录", "secret", [node(20, "隐藏目录的子项", "child")], is_show=0),
])
second_group = node(12, "门诊事务", "clinic", [
node(31, "业务台账", "ledger", component="clinic/ledger", perms="clinic.ledger/lists"),
# The visible menu alone is not a grant for this locally supported screen.
node(40, "就诊人资料", "people", component="consumer/lists/index", perms="user.user/lists"),
node(32, "操作按钮", "edit", type="A", perms="clinic.ledger/edit"),
])
menus = {"initial": [first_group, second_group], "empty": [], "clinic": [second_group]}
grants = {"initial": ["order.order/lists", "settle.ledger/lists", "settle.summary/lists",
"clinic.ledger/lists", "clinic.ledger/edit"],
"empty": [], "clinic": ["clinic.ledger/lists"]}
return {"user": {"id":991, "name":"菜单验收角色", "disable":0, "is_paw":1,
"need_bind_work_wechat":False, "root":0},
"permissions":grants[phase], "menu":menus[phase]}
class Offline:
def __init__(self, base):
self.base = base
self.phase = "initial"
self.calls = []
self.bad = []
self.documents = []
self.explicit = False
def route(self, route):
req = route.request
url = urlsplit(req.url)
key = (req.method, url.path)
def deny(reason):
self.bad.append((reason, *key))
route.abort()
if (url.scheme, url.netloc) == ("http", urlsplit(self.base).netloc):
if req.method == "GET" and (url.path.startswith("/admin/assets/") or
(req.resource_type == "document" and url.path.startswith("/admin/"))):
return route.continue_()
return deny("unexpected local request")
if (url.scheme, url.netloc) != ("https", HOST):
return deny("non-fixture origin")
if req.resource_type == "document":
if (not self.explicit or req.method != "GET" or url.path.startswith("/adminapi") or
any(s in req.url for s in (ACCOUNT, PASSWORD, TOKEN)) or
any(req.headers.get(h) for h in ("cookie", "token", "authorization"))):
return deny("unexpected official navigation")
self.documents.append(url.path)
return route.fulfill(content_type="text/html", body="<title>Offline official-site fixture</title>")
if url.path not in (LOGIN, SELF, ORDERS):
return deny("non-fixture API")
cors = {"Access-Control-Allow-Origin":self.base, "Access-Control-Allow-Methods":"GET,POST,OPTIONS",
"Access-Control-Allow-Headers":"token,version,content-type,accept", "Cache-Control":"no-store"}
if req.method == "OPTIONS":
return route.fulfill(status=204, headers=cors)
self.calls.append(key)
if req.headers.get("cookie"):
return deny("unexpected cookie")
if key == ("POST", LOGIN):
if req.post_data_json != {"account":ACCOUNT, "password":PASSWORD, "terminal":1}:
return deny("unexpected sign-in payload")
data = {"token":TOKEN, "is_paw":1, "need_bind_work_wechat":False}
elif req.headers.get("token") != TOKEN:
return deny("missing fixture token")
elif key == ("GET", SELF):
data = profile(self.phase)
elif key == ("GET", ORDERS) and self.phase == "initial":
number = FILTERED if parse_qs(url.query).get("order_no") == [FILTERED] else ROW
data = {"lists":[{"id":111, "order_no":number, "order_type":1, "status":2, "amount":"2.00",
"is_exempt":0, "creator":{"name":"演示"}, "prescription_orders":[]}],
"count":1, "extend":{}}
else:
return deny("method or permission mismatch")
route.fulfill(headers=cors, json={"code":1, "show":0, "msg":"", "data":data})
def exact(label):
return re.compile("^" + re.escape(label) + "$")
def open_group(parent, name):
title = parent.locator(".el-sub-menu__title").filter(has_text=exact(name))
expect(title).to_be_visible()
group = title.locator("..")
if "is-opened" not in (group.get_attribute("class") or "").split():
title.click()
expect(group).to_have_class(re.compile(r"\bis-opened\b"))
return group
def visit(page, parent, name, base, id_):
item = parent.locator(".el-menu-item").filter(has_text=exact(name))
item.click()
expect(page).to_have_url(re.compile("^" + re.escape(f"{base}/admin/nav/m-{id_}") + r"(?:\?|$)"))
def check(pw, args):
base = f"http://127.0.0.1:{args.port}"
mock, errors = Offline(base), []
with pw.chromium.launch(headless=True, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
]) as browser:
context = browser.new_context(service_workers="block", viewport={"width":1440,"height":950})
context.route("**/*", mock.route)
context.route_web_socket("**/*", lambda socket: (mock.bad.append(("websocket",)), socket.close()))
context.on("page", lambda p: p.on("pageerror", lambda error: errors.append(str(error))))
page = context.new_page()
page.goto(base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASSWORD)
assert not mock.calls, mock.calls
page.get_by_role("button", name="登录", exact=True).click()
menu = page.locator(".menu:visible")
refresh = page.locator("[data-refresh-online-menu]:visible")
roots = menu.locator(".el-menu").first
expect(roots.locator(":scope > .el-sub-menu > .el-sub-menu__title")).to_have_text(["收费事务","门诊事务"])
finance = open_group(menu, "收费事务")
settlement = open_group(finance, "对账事务")
expect(finance.locator(".el-sub-menu__title, .el-menu-item")).to_have_text(
["收费事务","对账事务","处方收款明细","业务台账","阶段汇总"])
visit(page, settlement, "处方收款明细", base, 72)
table = page.locator("main .el-table")
expect(table.get_by_text(ROW, exact=True)).to_be_visible()
page.get_by_placeholder("请输入订单号").fill(FILTERED)
page.get_by_role("button", name="查询", exact=True).click()
expect(table.get_by_text(FILTERED, exact=True)).to_be_visible()
expect(table.get_by_text(ROW, exact=True)).to_have_count(0)
page.screenshot(path=str(args.out/"menu-orders.png"))
calls = list(mock.calls)
visit(page, settlement, "业务台账", base, 35)
main = page.locator("main")
expect(main.get_by_text("业务台账", exact=True)).to_be_visible()
expect(main).to_contain_text("正式后台")
clinic = open_group(menu, "门诊事务")
expect(clinic.locator(".el-menu-item")).to_have_text(["业务台账","就诊人资料"])
visit(page, clinic, "就诊人资料", base, 40)
expect(main).to_contain_text("正式后台")
expect(main.locator(".el-table")).to_have_count(0)
visit(page, clinic, "业务台账", base, 31)
expect(main.get_by_text("业务台账", exact=True)).to_be_visible()
expect(main).to_contain_text("正式后台")
page.wait_for_load_state("networkidle")
assert mock.calls == calls and not mock.documents, (mock.calls, mock.documents)
page.screenshot(path=str(args.out/"menu-official-only.png"))
# Revoke while the real local table is mounted: old rows and navigation must disappear.
settlement = open_group(open_group(menu, "收费事务"), "对账事务")
visit(page, settlement, "处方收款明细", base, 72)
expect(table).to_be_visible()
page.wait_for_load_state("networkidle")
before = list(mock.calls)
mock.phase = "empty"
refresh.click()
expect(menu.locator(".el-menu-item, .el-sub-menu__title")).to_have_count(0)
expect(main.locator(".el-table")).to_have_count(0)
expect(main).not_to_contain_text("OFFLINE-")
page.wait_for_load_state("networkidle")
assert mock.calls[len(before):] == [("GET", SELF)], mock.calls
page.screenshot(path=str(args.out/"menu-empty.png"))
# Same session receives a new, unadapted-only tree; never silently open the official site.
mock.phase = "clinic"
refresh.click()
clinic = open_group(menu, "门诊事务")
visit(page, clinic, "业务台账", base, 31)
expect(menu.locator(".el-sub-menu__title")).to_have_text(["门诊事务"])
expect(main).to_contain_text("正式后台")
page.wait_for_load_state("networkidle")
assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.documents
link = main.get_by_role("link", name=re.compile("正式后台")).or_(
main.get_by_role("button", name=re.compile("正式后台")))
expect(link).to_be_visible()
mock.explicit = True
with context.expect_event("requestfinished", predicate=lambda r:
urlsplit(r.url).netloc == HOST and r.resource_type == "document"):
link.click()
assert mock.documents == ["/admin/clinic/ledger"], mock.documents
assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.bad and not errors, (
mock.calls, mock.bad, errors)
return {"offline_menu_contract":"PASS", "intercepted_api_calls":mock.calls,
"intercepted_official_navigation":mock.documents, "unexpected":mock.bad, "page_errors":errors}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--port", type=int, default=5179)
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
with sync_playwright() as pw:
print(json.dumps(check(pw, args), ensure_ascii=False))
+24
View File
@@ -0,0 +1,24 @@
// Standalone first-party UI; no local API proxy or database client. Never load .env or the default Vite config.
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { mkdir } from 'node:fs/promises'
import { build } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
const here = path.dirname(fileURLToPath(import.meta.url)), root = path.dirname(here)
process.chdir(root)
export const outDir = path.join(root,'node_modules/.zyt-live-read/dist')
await mkdir(outDir, {recursive:true})
await build({ root, mode:'live-readonly', configFile:false, envFile:false, envPrefix:'ZYT_LOCAL_NO_EXPOSE_', publicDir:false, base:'/admin/',
cacheDir:path.join(root,'node_modules/.zyt-live-read/cache'),
define:{'import.meta.env.VITE_APP_BASE_URL':JSON.stringify('')},
resolve:{alias:[{find:/^@\/utils\/request(?:\/index)?$/,replacement:path.join(here,'transport.ts')},{find:/^@\/stores\/modules\/user$/,replacement:path.join(here,'user.ts')},{find:/^@\/router$/,replacement:path.join(here,'router.ts')},{find:/^\.\/breadcrumb\.vue$/,replacement:path.join(here,'OnlineBreadcrumb.vue')},{find:/^\.\/user-drop-down\.vue$/,replacement:path.join(here,'Identity.vue')},{find:'@',replacement:path.join(root,'src')}]},
plugins:[vue(),vueJsx(),createSvgIconsPlugin({iconDirs:[path.join(root,'src/assets/icons')],symbolId:'local-icon-[dir]-[name]'}),AutoImport({imports:['vue','vue-router'],resolvers:[ElementPlusResolver({importStyle:false})],dts:false}),Components({dirs:[path.join(root,'src/components')],directoryAsNamespace:true,dts:false}),vueSetupExtend()],
build:{outDir,emptyOutDir:true,sourcemap:false,reportCompressedSize:false,rollupOptions:{input:path.join(here,'index.html')}},
css:{preprocessorOptions:{scss:{api:'modern-compiler'}}}
})
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh-CN" data-admin-ui="v2"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>甄养堂 · 正式数据只读预览</title><link rel="icon" href="data:,"></head><body><div id="app"></div><script type="module" src="./main.ts"></script></body></html>
+21
View File
@@ -0,0 +1,21 @@
import 'virtual:svg-icons-register'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import '@/styles/index.scss'
import '@/install/plugins/echart'
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import installIcons from '@/install/plugins/element'
import perms from '@/install/directives/perms'
import store from '@/stores'
import useAppStore from '@/stores/modules/app'
import useUserStore from './user'
import Root from '../local-preview/Root.vue'
import router from './router'
import mark from '../local-preview/preview-mark-art.svg'
const app=createApp(Root);app.use(store);app.use(ElementPlus);installIcons(app);app.directive('perms',perms)
useAppStore().$patch({configFetchAttempted:true,config:{web_name:'甄养堂管理后台',web_logo:mark}})
window.addEventListener('live-readonly:session-ended',()=>{ if(useUserStore().ready){useUserStore().$reset(); location.replace('/admin/login')} })
// A browser back/forward cache must not resurrect a signed-out / expired clinical view.
window.addEventListener('pageshow',e=>{if(e.persisted)location.replace('/admin/login')})
app.use(router);router.isReady().then(()=>app.mount('#app'))
+141
View File
@@ -0,0 +1,141 @@
import * as elementIcons from '@element-plus/icons-vue'
import { OFFICIAL_ORIGIN } from './policy.mjs'
import { reviewedMenuKey } from './resources.mjs'
// This is presentation data, not a grant list. MenuLogic::getMenuByAdminId
// already orders each role's assigned tree by sort DESC, id ASC. Never flatten,
// re-sort by component, or infer a grant from a path, title or menu id.
const on = value => value === 1 || value === '1' || value === true
const off = value => value === 0 || value === '0' || value === false
const control = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u
const segment = /^[\p{L}\p{N}_-][\p{L}\p{N}_.-]*$/u
const adminBase = OFFICIAL_ORIGIN + '/admin/'
function menuIcon(value) {
if (typeof value !== 'string') return ''
if (/^local-icon-[\w-]+$/.test(value)) return value // same-document SVG fragment
// The original <icon> resolves the suffix as a Vue component; only actual
// registered icon names may use this branch (never e.g. el-icon-RouterView).
if (/^el-icon-[a-z][\w-]*$/i.test(value) && value.startsWith('el-icon-')) {
// resolveComponent tries both the supplied name and its PascalCase
// variant. Older menu rows use e.g. el-icon-arrow-down or el-icon-house.
const camel = value.slice(8).replace(/-(\w)/g, (_, c) => c.toUpperCase())
const name = camel[0].toUpperCase() + camel.slice(1)
if (Object.hasOwn(elementIcons, name)) return 'el-icon-' + name
}
return ''
}
// Keep ordinary menu defaults (the official editor accepts JSON or k=v).
// URLs are not a credential transport or a second way to issue a request.
// In particular, do not pass through redirect, tokens, blobs, arbitrary keys
// or nested objects. Business requests still have their own transport policy.
const queryKeys = new Set(('id name type tab status category channel source order_type time_type ' +
'date start_date end_date doctor_id dept_id assistant_id page page_no page_size').split(' '))
const intKey = /^(?:id|.*_id|page|page_no|page_size)$/
function menuQuery(input) {
if (typeof input !== 'string' || !input || input.length > 2048) return {}
let pairs
if (input.trimStart().startsWith('{')) {
try { pairs = Object.entries(JSON.parse(input)) } catch { return {} }
} else {
if (!input.includes('=')) return {}
pairs = new URLSearchParams(input)
}
const query = {}
for (const [key, value] of pairs) {
if (!queryKeys.has(key) || (typeof value !== 'string' && typeof value !== 'number')) continue
const str = String(value)
if (intKey.test(key) ? !/^[1-9]\d{0,14}$/.test(str) :
!/^[\p{L}\p{N} _-]{1,80}$/u.test(str)) continue
query[key] = str
}
return query
}
// Resolve relative to the authorized parent's actual route, never to a local
// alias. Only simple path segments can be joined under the fixed admin base.
// A bad path remains a visible menu node with no action; it is not repaired
// into a guessed destination. An explicit http(s) URL is always a handoff.
function destination(raw, parent) {
if (typeof raw !== 'string' || !raw || raw !== raw.trim() || raw.length > 2048 ||
raw.includes('\\') || control.test(raw)) return null
if (/^https?:\/\/[^/]/i.test(raw)) {
try {
const url = new URL(raw)
if (url.username || url.password || !url.hostname) return null
// A menu may link to a public site, but never hand off a production
// API/action URL (even a GET can initiate a business write).
if (url.hostname === new URL(OFFICIAL_ORIGIN).hostname &&
(url.origin !== OFFICIAL_ORIGIN || !/^\/admin(?:\/|$)/.test(url.pathname))) return null
const query = menuQuery(url.search)
url.search = ''
// A fragment can itself contain tokens or a second query string.
if (url.hash && !/^#[\w-]+$/.test(url.hash)) url.hash = ''
return { href: url.href, external: true, query }
} catch { return null }
}
if (!parent || parent.external || raw.includes('//')) return null
const path = raw.replace(/^\/|\/$/g, '')
if (!path || !path.split('/').every(s => segment.test(s))) return null
const href = parent.href.replace(/\/$/, '') + '/' + path.split('/').map(encodeURIComponent).join('/')
return { href, external: false }
}
function stableId(item, parentId, used) {
let base
if ((typeof item.id === 'number' || typeof item.id === 'string') && /^[1-9]\d*$/.test(String(item.id)) &&
Number.isSafeInteger(Number(item.id))) {
base = 'm-' + item.id
} else {
// Older fixtures need not have DB ids. Do not put raw upstream input in
// a local URL or make all sibling links change when one is added.
const seed = parentId + '/' + (typeof item.paths === 'string' ? item.paths : '')
let hash = 2166136261
for (let i = 0; i < seed.length; i++) hash = Math.imul(hash ^ seed.charCodeAt(i), 16777619)
base = 'p-' + (hash >>> 0).toString(36)
}
let id = base
for (let n = 2; used.has(id); n++) id = base + '-' + n
used.add(id)
return id
}
export function buildNavigation(menu, keys) {
const allowed = new Set(Array.isArray(keys) ? keys : [])
const entries = [], used = new Set(), ancestors = new Set()
function visit(rows, parent, parentId, parents) {
const nodes = []
for (const item of Array.isArray(rows) ? rows : []) {
if (!item || (item.type !== 'M' && item.type !== 'C') || ancestors.has(item) ||
!on(item.is_show) || (item.is_disable !== undefined && !off(item.is_disable))) continue
const id = stableId(item, parentId, used)
const target = destination(item.paths, parent)
const query = { ...target?.query, ...menuQuery(item.params) }
const fallback = typeof item.paths === 'string' && segment.test(item.paths) ? item.paths : id
const title = typeof item.name === 'string' && item.name.trim() && !control.test(item.name) ? item.name : fallback
const node = { id, title, icon: menuIcon(item.icon), ...(target && Object.keys(query).length ? { query } : {}) }
const breadcrumbs = [...parents, title]
ancestors.add(item)
const children = visit(item.children, target, id, breadcrumbs)
ancestors.delete(item)
if (children.length) {
node.children = children
} else {
// Official sidebar renders a folder with no visible children as
// a leaf. It is not a reviewed local component.
const candidate = target && !target.external ? reviewedMenuKey(item) : null
const liveKey = allowed.has(candidate) ? candidate : null
const url = target ? new URL(target.href) : null
if (url) url.search = new URLSearchParams(query).toString()
entries.push({ ...node, breadcrumbs, liveKey, officialHref: url?.href ?? null,
external: target?.external ?? false })
}
nodes.push(node)
}
return nodes
}
const tree = visit(menu, { href: adminBase, external: false }, '', [])
return { tree, entries, firstId: entries.find(e => e.liveKey)?.id ?? entries[0]?.id ?? null }
}
+139
View File
@@ -0,0 +1,139 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { buildNavigation } from './navigation.mjs'
import { projectResources } from './resources.mjs'
import { OFFICIAL_ORIGIN } from './policy.mjs'
const base = OFFICIAL_ORIGIN + '/admin/'
const leaf = (id, name, paths, more = {}) => ({ type: 'C', id, name, paths,
component: 'order/index', perms: 'order.order/lists', is_show: 1, is_disable: 0, ...more })
const group = (id, name, paths, children, more) => ({ ...leaf(id, name, paths), type: 'M', children, ...more })
const shape = tree => tree.map(node => [node.id, node.title, node.children ? shape(node.children) : null])
test('preserves server order, real titles/icons, nested and duplicate menu placements independent of live support', () => {
const menu = [
group(100, '诊疗管理', '/clinics/', [
leaf(200, '随访', '/follow/up/', { component: 'other/follow', perms: 'other.follow/lists', sort: 30 }),
group(101, '组内管理', 'team', [leaf(9, '台账', 'bills', { icon: 'local-icon-qianbao' })])
], { icon: 'el-icon-Lock' }),
group(20, '运营管理', 'ops', [
leaf(8, '台账', 'order', { icon: 'el-icon-Tickets' }),
leaf(7, '订单回访', 'revisit', { component: '/order/index/' })
], { sort: 999 })
]
const { tree, entries, firstId } = buildNavigation(menu, ['orders'])
assert.deepEqual(shape(tree), [
['m-100', '诊疗管理', [['m-200', '随访', null], ['m-101', '组内管理', [['m-9', '台账', null]]]]],
['m-20', '运营管理', [['m-8', '台账', null], ['m-7', '订单回访', null]]]
])
assert.deepEqual(entries.map(e => [e.id, e.liveKey, e.officialHref]), [
['m-200', null, base + 'clinics/follow/up'], ['m-9', 'orders', base + 'clinics/team/bills'],
['m-8', 'orders', base + 'ops/order'], ['m-7', 'orders', base + 'ops/revisit']
])
assert.equal(firstId, 'm-9')
assert.deepEqual(entries[1].breadcrumbs, ['诊疗管理', '组内管理', '台账'])
assert.equal(tree[0].icon, 'el-icon-Lock')
assert.equal(entries[1].icon, 'local-icon-qianbao')
assert.equal(entries[2].icon, 'el-icon-Tickets')
})
test('prunes whole disabled/hidden/button branches; menu with visible children is a group; empty visible directory remains', () => {
const m = leaf(1, '订单', 'order')
const menu = [
group(4, '隐藏', 'hide', [m], { is_show: '0' }), group(5, '停用', 'stop', [m], { is_disable: '1' }),
group(6, '按钮', 'action', [m], { type: 'A' }),
leaf(7, '目录页面', 'page', { children: [leaf(8, '订单查询', 'orders', { is_show: '1', is_disable: '0' })] }),
group(9, '权限管理', 'acl', [leaf(10, '不可见', 'hidden', { is_show: false })]),
leaf(11, '禁用', 'notHere', { is_disable: true }), leaf(12, '隐藏', 'hidden', { is_show: 0 })
]
const { tree, entries } = buildNavigation(menu, ['orders'])
assert.deepEqual(shape(tree), [['m-7', '目录页面', [['m-8', '订单查询', null]]], ['m-9', '权限管理', null]])
assert.deepEqual(entries.map(e => [e.id, e.liveKey]), [['m-8', 'orders'], ['m-9', null]])
assert.equal(entries[1].officialHref, base + 'acl')
})
test('navigation never expands keys; exact component, per-instance permission and authorized key all required', () => {
const m = leaf(1, '订单', 'order')
const menu = [m, { ...m, id: 2, perms: 'order.order/edit' }, { ...m, id: 3, component: 'alt/order/index' },
{ ...m, id: 4, component: 'https://example.invalid/file.vue' },
{ ...m, id: 5, paths: 'https://example.invalid/order' }]
const self = { user: { id: 64 }, menu, permissions: ['order.order/lists'] }
const { keys } = projectResources(self)
assert.deepEqual(keys, ['orders'])
assert.deepEqual(buildNavigation(menu, keys).entries.map(x => x.liveKey), ['orders', null, null, null, null])
for (const keys of [[], ['*'], ['ORDER'], undefined]) {
const n = buildNavigation(menu, keys)
assert.deepEqual(n.entries.map(x => x.liveKey), [null, null, null, null, null])
assert.equal(n.firstId, 'm-1')
}
assert.ok(!JSON.stringify(buildNavigation(menu, keys)).includes('file.vue'))
})
test('safe dedicated params field accepts both official syntaxes without passing redirects/credentials/second queries', () => {
const menu = [
leaf(1, '订单一', '/order', { params: '{"id":42,"type":"分类","name":"张 三","token":"SECRET","redirect":"https://evil.invalid"}' }),
leaf(2, '订单二', 'other', { params: 'tab=pending&next=evil&password=SECRET&status=1&__proto__=x&date=2026-12-01' }),
leaf(3, '详情', 'detail', { params: '{"id":"-1","name":{},"type":"//evil.invalid","token":"SECRET"}' }),
leaf(4, '异常', 'bad', { params: '{"tab":' }),
leaf(5, '双重编码', 'polluted', { params: 'tab=ok%26token%3DSECRET&type=%252f%252fother.invalid' })
]
const n = buildNavigation(menu, ['orders'])
assert.deepEqual(n.entries[0].query, { id: '42', type: '分类', name: '张 三' })
assert.deepEqual(n.tree[0].query, n.entries[0].query)
const directory = buildNavigation([group(900, '目录', 'dir', [menu[0]], { params: 'tab=all&token=SECRET' })], [])
assert.deepEqual(directory.tree[0].query, { tab: 'all' })
assert.deepEqual(directory.tree[0].children[0].query, n.entries[0].query)
assert.deepEqual(Object.fromEntries(new URL(n.entries[0].officialHref).searchParams), n.entries[0].query)
assert.deepEqual(n.entries[1].query, { tab: 'pending', status: '1', date: '2026-12-01' })
assert.equal(n.entries[2].officialHref, base + 'detail')
assert.equal(n.entries[3].query, undefined)
assert.equal(n.entries[4].query, undefined)
assert.ok(!JSON.stringify(n).includes('SECRET'))
})
test('invalid paths remain visible but inert, including descendants; explicit web links are distinct from local screens', () => {
const paths = ['../x', '%2e%2e/x', '/x//else', 'javascript:alert(1)', 'data:text/html,body',
'file:///tmp/none', 'mailto:name@example.invalid', '//elsewhere.invalid/path', 'https:///bad.example',
'https://user:secret@example.invalid', '\\evil', 'x?next=z', 'x#section', '\u0000path', '/%2felse']
const bad = paths.map((p, i) => leaf(i + 20, '未开放', p))
const menu = [...bad, group(1, '无效父', '../unsafe', [leaf(2, '子菜单', 'order')]),
leaf(3, '说明', 'https://docs.example.invalid/start?tab=first&token=SECRET#info'),
leaf(4, '帮助', 'http://docs.example.invalid/help', { params: 'type=admin' })]
const n = buildNavigation(menu, ['orders'])
assert.equal(n.entries.length, bad.length + 3)
for (const e of n.entries.slice(0, -2)) {
assert.equal(e.officialHref, null); assert.equal(e.liveKey, null)
}
assert.deepEqual(n.entries.slice(-2).map(x => [x.external, x.officialHref, x.liveKey]), [
[true, 'https://docs.example.invalid/start?tab=first#info', null],
[true, 'http://docs.example.invalid/help?type=admin', null]
])
assert.ok(!JSON.stringify(n).includes('SECRET'))
})
test('DB ids stable across reordering, missing ids path-derived, repeated paths distinct, empty inputs deterministic', () => {
const some = [leaf(null, '', 'first'), leaf('5', '二', 'second'), leaf(null, '三', 'third')]
const ids = rows => new Map(buildNavigation(rows, []).entries.map(e => [e.title, e.id]))
assert.deepEqual(ids(some), ids(some.toReversed()))
assert.match(ids(some).get('first'), /^p-[a-z0-9]+$/)
assert.equal(ids(some).get('二'), 'm-5')
const duplicated = [some[1], some[1], some[0], some[0]]
const e = buildNavigation(duplicated, []).entries
assert.equal(new Set(e.map(x => x.id)).size, 4)
for (const menu of [undefined, {}, [], [null, { type: 'A' }]]) {
assert.deepEqual(buildNavigation(menu, []), { tree: [], entries: [], firstId: null })
}
})
test('only registered Element icons or local SVG fragments reach the production dynamic icon component', () => {
const icons = ['el-icon-RouterView', 'el-icon-Iframe', 'local-icon-x#url', 'https://example.invalid/art.svg',
'el-icon-User', 'local-icon-set_pay', 'el-icon-house', 'el-icon-arrow-down', 'el-icon-arrowDown']
assert.deepEqual(buildNavigation(icons.map((icon, i) => leaf(i + 1, '名称', 'icon', { icon })), []).entries.map(e => e.icon),
['', '', '', '', 'el-icon-User', 'local-icon-set_pay', 'el-icon-House', 'el-icon-ArrowDown', 'el-icon-ArrowDown'])
})
test('an upstream absolute API action remains visible but never becomes a clickable handoff', () => {
const {entries}=buildNavigation([leaf(37,'同步配置',OFFICIAL_ORIGIN+'/adminapi/operation/run')],['orders'])
assert.equal(entries[0].title,'同步配置');assert.equal(entries[0].officialHref,null);assert.equal(entries[0].liveKey,null)
})
+75
View File
@@ -0,0 +1,75 @@
// Enumerate operations rather than assuming every GET is read-only. Never accept a base URL.
export const OFFICIAL_ORIGIN = 'https://admin.zhenyangtang.com.cn'
const oneOf = (...values) => v => values.includes(v)
const int = v => /^[1-9]\d{0,14}$/.test(v) && Number.isSafeInteger(Number(v))
const text = v => typeof v === 'string' && v.length <= 120 && !/[\u0000-\u001f\u007f]/.test(v)
const day = v => /^\d{4}-\d{2}-\d{2}$/.test(v) &&
Number.isFinite(Date.parse(v)) && new Date(v).toISOString().slice(0, 10) === v
const timestamp = v => day(v) || (
/^\d{4}-\d{2}-\d{2} (?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(v) && day(v.slice(0, 10))
)
const page = {page_no: int, page_size: int}
const range = {create_time_start: timestamp, create_time_end: timestamp}
const operations = new Map([
['/auth.admin/mySelf', [null, {}]],
['/order.order/orderStats', ['workbench', {days: oneOf('0','7','30'), order_type: oneOf('-1','0','1','2','3','4','5','6','7','8')}]],
['/tcm.diagnosis/assistantDiagnosisStats', ['workbench', {days: oneOf('0','7','14','30')}]],
['/order.order/lists', ['orders', {...page, ...range, order_no: text, patient_keyword: text, assistant_id: int,
order_type: oneOf('1','2','3','4','5','6','7','8'), status: oneOf('1','2','3','4','5'),
patient_association: oneOf('associated','pending')}]],
['/order.order/todayRevenue', ['orders', {}]],
['/tcm.diagnosis/getAssistants', ['orders', {}]],
['/user.user/lists', ['members', {...page, ...range, channel: oneOf('1','2','3','4','5','6'), keyword: text}]],
['/user.user/detail', ['memberDetail', {id: int}]],
['/auth.admin/lists', ['roster', {...page, role_id: oneOf('1'), exclude_disabled: oneOf('1'), apply_data_scope: oneOf('1')}]],
['/doctor.roster/lists', ['roster', {start_date: day, end_date: day, doctor_id: int}]],
['/dept.dept/all', ['deptStats', {apply_data_scope: oneOf('1')}]],
['/doctor.statistics/deptLists', ['deptStats', {time_type: oneOf('today','week','month','custom'), dept_id: int,
start_date: day, end_date: day, ...page}]]
])
function rejectQuery() { throw new Error('该请求不在只读预览的查询范围内。') }
function plain(o) {
return !!o && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null)
}
export function prepareRequest(method, path, params = {}) {
if (!plain(params)) rejectQuery()
if (method === 'POST' && path === '/login/account') {
const {account, password, terminal} = params
if (Object.keys(params).some(k => !['account', 'password', 'terminal'].includes(k)) ||
typeof account !== 'string' || !account.trim() || !text(account) ||
typeof password !== 'string' || !password || password.length > 1024 ||
(terminal !== undefined && terminal !== 1)) rejectQuery()
// The original admin sign-in is a JSON POST with terminal=1, not a credential-bearing URL.
return {resource: null, query: null, body: JSON.stringify({account: account.trim(), password, terminal: 1})}
}
if (method !== 'GET' || !operations.has(path)) rejectQuery()
const [resource, fields] = operations.get(path)
const query = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (!Object.hasOwn(fields, key)) rejectQuery() // including unknown empty keys
if (value == null || value === '') continue
if (typeof value !== 'number' && typeof value !== 'string') rejectQuery()
const s = String(value)
if (!fields[key](s)) rejectQuery()
query.set(key, key === 'page_size' ? String(Math.min(Number(s), 100)) : s)
}
if (path === '/auth.admin/lists') {
if (query.get('role_id') !== '1' || query.get('exclude_disabled') !== '1') rejectQuery()
query.set('apply_data_scope', '1')
} else if (path === '/dept.dept/all') {
query.set('apply_data_scope', '1')
} else if (path === '/user.user/detail' && !query.has('id')) {
rejectQuery()
} else if (path === '/doctor.roster/lists') {
const start = query.get('start_date'), end = query.get('end_date')
if (!query.has('doctor_id') || !start || !end || end < start || Date.parse(end) - Date.parse(start) > 6 * 86400000) rejectQuery()
} else if (path === '/doctor.statistics/deptLists') {
const start = query.get('start_date'), end = query.get('end_date')
if (query.get('time_type') === 'custom') {
if (!start || !end || end < start || Date.parse(end) - Date.parse(start) > 365 * 86400000) rejectQuery()
} else if (start || end) rejectQuery()
}
return {resource, query, body: undefined}
}
+86
View File
@@ -0,0 +1,86 @@
// Page component IDs are the values used by admin/src/router/index.ts, not URL
// slugs or labels. The list is closed: adding a page requires a read-path audit.
const pages = [
{ key: 'workbench', component: 'workbench/index', permission: 'workbench/index',
requires: ['order.order/orderStats', 'tcm.diagnosis/assistantDiagnosisStats'] },
{ key: 'orders', component: 'order/index', permission: 'order.order/lists' },
{ key: 'members', component: 'consumer/lists/index', permission: 'user.user/lists' },
{ key: 'memberDetail', component: 'consumer/lists/detail', permission: 'user.user/detail' },
{ key: 'roster', component: 'doctor/roster', permission: 'doctor.roster/lists',
requires: ['auth.admin/lists'] },
// StatisticsLists::getDeptStatistics aggregates all departments without data scope.
{ key: 'deptStats', component: 'doctor/dept-tongji', permission: 'doctor.statistics/deptLists',
requires: ['dept.dept/all'], rootOnly: true }
]
const byComponent = new Map(pages.map(page => [page.component, page]))
// A rendering match is not a permission grant: callers must also intersect the
// result with the independently authorized resource keys from mySelf.
export function reviewedMenuKey(item) {
if (item?.type !== 'C' || typeof item.component !== 'string') return null
const page = byComponent.get(item.component.replace(/^\/+|\/+$/g, ''))
return page && item.perms === page.permission ? page.key : null
}
const on = value => value === true || value === 1 || value === '1'
const off = value => value === false || value === 0 || value === '0'
const validId = value => (typeof value === 'number' || typeof value === 'string') &&
/^[1-9]\d*$/.test(String(value)) && Number.isSafeInteger(Number(value))
const internal = path => typeof path === 'string' && path.trim() !== '' &&
!/^(?:[a-z][a-z\d+.-]*:|[/\\]{2})/i.test(path.trim())
/**
* Reduce the authenticated upstream AdminController::mySelf **data** object to
* safe page/action IDs. Never return the raw profile, menu, route, or '*'.
* These IDs constrain, but do not replace, upstream authorization and row scope.
*/
export function projectResources(mySelf) {
const result = { keys: [], perms: [] }
const user = mySelf?.user
if (!validId(user?.id) || (user.disable !== undefined && !off(user.disable)) ||
(user.is_paw !== undefined && !on(user.is_paw)) ||
(user.need_bind_work_wechat !== undefined && !off(user.need_bind_work_wechat)) ||
!Array.isArray(mySelf.menu) || !Array.isArray(mySelf.permissions)) return result
const isRoot = user.root === 1 || user.root === '1'
const granted = new Set(mySelf.permissions)
const selected = new Set(), registered = new Set(), seen = new Set()
const stack = [...mySelf.menu]
while (stack.length) {
const item = stack.pop()
if (!item || typeof item !== 'object' || seen.has(item)) continue
seen.add(item)
if ((item.type !== 'M' && item.type !== 'C') || !internal(item.paths) ||
(item.is_disable !== undefined && !off(item.is_disable))) continue
const visible = on(item.is_show)
if (item.type === 'C') {
const component = typeof item.component === 'string' ? item.component.replace(/^\/+|\/+$/g, '') : ''
const page = byComponent.get(component)
// AuthLogic can also return '*' to a NON-root user with all currently
// registered grants. A registered C in this user's tree is evidence;
// never use a non-root wildcard to infer unregistered auxiliary APIs.
if (typeof item.perms === 'string' && item.perms) registered.add(item.perms)
if (page && item.perms === page.permission &&
(visible || (page.key === 'memberDetail' && off(item.is_show)))) selected.add(page.key)
}
if (visible && Array.isArray(item.children)) {
for (const child of item.children) stack.push(child)
}
}
const allows = perm => granted.has(perm) || (granted.has('*') && (isRoot || registered.has(perm)))
const readonly = new Set()
for (const page of pages) {
if (!selected.has(page.key) || (page.rootOnly && !isRoot) ||
(page.key === 'memberDetail' && !result.keys.includes('members'))) continue
const required = [page.permission, ...(page.requires || [])]
if (!required.every(allows)) continue
result.keys.push(page.key)
for (const perm of required) readonly.add(perm)
if (page.key === 'orders') {
if (allows('tcm.diagnosis/getAssistants')) readonly.add('tcm.diagnosis/getAssistants')
// The supervisor aggregate in OrderLogic::todayRevenue ignores row scope.
if (isRoot && allows('order.order/todayRevenue')) readonly.add('order.order/todayRevenue')
}
}
result.perms = [...readonly]
return result
}
+93
View File
@@ -0,0 +1,93 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { projectResources } from './resources.mjs'
const wb = 'workbench/index', order = 'order.order/lists', member = 'user.user/lists'
const detail = 'user.user/detail', doctors = 'auth.admin/lists', roster = 'doctor.roster/lists'
const dept = 'doctor.statistics/deptLists', depts = 'dept.dept/all'
const wbStats = ['order.order/orderStats', 'tcm.diagnosis/assistantDiagnosisStats']
const assistants = 'tcm.diagnosis/getAssistants', revenue = 'order.order/todayRevenue'
const empty = { keys: [], perms: [] }
const leaf = (component, perms, fields = {}) => ({
type: 'C', component, perms, paths: 'entry', is_disable: 0, is_show: 1, ...fields
})
const catalog = (children, fields = {}) => ({ type: 'M', paths: 'admin', is_disable: 0, is_show: 1, children, ...fields })
const lists = leaf('consumer/lists/index', member), hidden = leaf('consumer/lists/detail', detail, { is_show: 0 })
const orders = leaf('order/index', order), department = leaf('doctor/dept-tongji', dept)
const identity = (menu, permissions, user = {}) => ({
user: { id: 42, root: 0, disable: 0, is_paw: 1, need_bind_work_wechat: false, ...user },
menu, permissions
})
const check = (self, keys, perms) => {
const result = projectResources(self)
assert.deepEqual(Object.keys(result).sort(), ['keys', 'perms'])
assert.deepEqual([...result.keys].sort(), keys.sort())
assert.deepEqual([...result.perms].sort(), perms.sort())
}
test('invalid or empty upstream identity/menu/grants never unlock even a root route', () => {
for (const self of [undefined, {}, { menu: [orders], permissions: ['*'] },
{ data: identity([orders], ['*']) }, identity([], ['*'], { root: 1 }),
identity([orders], []), identity([orders], '*'), identity([orders], [order], { id: 0 }),
identity([orders], [order], { disable: '1' }), identity([orders], [order], { is_paw: 0 }),
identity([orders], [order], { need_bind_work_wechat: true })]) {
assert.deepEqual(projectResources(self), empty)
}
})
test('a real visible menu with exact page and authority is required; hidden/disabled ancestors, external links, buttons and aliases are ignored', () => {
const menu = [
catalog([orders], { is_show: '0' }), catalog([orders], { is_disable: '1' }),
catalog([orders], { paths: 'https://example.invalid' }),
{ ...orders, type: 'A' }, { ...orders, is_show: 0 }, { ...orders, is_show: 'maybe' },
{ ...orders, is_disable: 1 }, { ...orders, perms: 'order.order/create' },
{ ...orders, component: 'elsewhere/order/index' }, { ...orders, paths: '//example.invalid' },
{ ...orders, component: '', name: '订单列表', paths: 'order' }, lists
]
check(identity(menu, [order]), [], [])
check(identity([catalog([{ ...lists, component: '/consumer/lists/index/' }, lists])], [member]), ['members'], [member])
})
test('hidden detail route needs its own assigned menu + permission and a visible member list', () => {
check(identity([hidden], [member, detail]), [], [])
check(identity([lists], [member, detail]), ['members'], [member])
check(identity([hidden, lists], [member]), ['members'], [member])
check(identity([catalog([hidden, lists])], [member, detail, 'user.user/edit', 'user.user/adjustMoney']),
['members', 'memberDetail'], [member, detail])
})
test('order list does not imply export, view-detail write, all-employee reports, or unregistered auxiliary grants', () => {
check(identity([orders], [order, 'order.order/detail', 'order.order/export', 'order.order/actionLogStats',
'order.order/pay', 'order.order/edit', 'order.order/create', revenue]), ['orders'], [order])
check(identity([orders], [order, assistants, revenue]), ['orders'], [order, assistants])
check(identity([orders], ['*'], { root: '1' }), ['orders'], [order, assistants, revenue])
})
test('workbench requires both scoped real statistics; roster requires doctor-directory access', () => {
const pages = [leaf('workbench/index', wb), leaf('doctor/roster', roster)]
check(identity(pages, [wb, roster]), [], [])
check(identity(pages, [wb, wbStats[0], roster, doctors]), ['roster'], [roster, doctors])
check(identity(pages, [wb, ...wbStats, roster, doctors]), ['workbench', 'roster'], [wb, ...wbStats, roster, doctors])
})
test('a non-root all-registered wildcard cannot infer auxiliary API grants absent from the assigned menu', () => {
check(identity([orders, leaf('doctor/roster', roster)], ['*']),
['orders'], [order])
check(identity([orders, leaf('doctor/roster', roster), leaf('permission/admin/index', doctors)], ['*']),
['orders', 'roster'], [order, roster, doctors])
})
test('unscoped department aggregation requires real root plus the specific assigned menu and authorizations', () => {
check(identity([department], [dept, depts]), [], [])
check(identity([department], ['*']), [], [])
check(identity([department], [dept], { root: 1 }), [], [])
check(identity([department], [dept, depts], { root: 1 }), ['deptStats'], [dept, depts])
})
test('only explicit reviewed resources are projected; never pass wildcard, raw profile/menu, ledger or arbitrary grants through', () => {
const permissions = ['*'], pages = [leaf('workbench/index', wb), orders, lists, hidden,
leaf('doctor/roster', roster), department, leaf('local-preview/AppointmentLedger', 'doctor.appointment/lists')]
check(identity([catalog(pages)], permissions, { root: 1, phone: 'sensitive_field' }),
['workbench', 'orders', 'members', 'memberDetail', 'roster', 'deptStats'],
[wb, ...wbStats, order, assistants, revenue, member, detail, roster, doctors, dept, depts])
})
+87
View File
@@ -0,0 +1,87 @@
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/default/index.vue'
import useUserStore from './user'
import { screens } from './screens'
const router = createRouter({
history: createWebHistory('/admin/'),
routes: [
{ path: '/login', component: () => import('@/views/account/login.vue') },
{
path: '/',
component: Layout,
children: [
{
path: '',
name: 'live-home',
component: () => import('./NoAccess.vue'),
meta: { hideTab: true }
},
{
path: '/nav/:menuId',
name: 'live-menu',
component: () => import('./OnlinePage.vue')
},
// Keep the reviewed hidden drill-down separate from the visible menu.
{
path: '/members/detail',
name: 'live-member-detail',
component: () => import('@/views/consumer/lists/detail.vue'),
meta: { title: '用户详情', key: 'memberDetail' }
},
...screens
.filter((s) => !s.hidden)
.map((s) => ({
path: s.path,
redirect: () => {
const e = Object.values(useUserStore().entries).find(
(e) => e.liveKey === s.key
)
return e
? {
name: 'live-menu',
params: { menuId: e.id },
query: e.query || {}
}
: '/unavailable'
}
})),
{
path: '/unavailable',
name: 'live-unavailable',
component: () => import('./NoAccess.vue'),
meta: { hideTab: true }
}
]
},
{ path: '/:notfound(.*)*', redirect: '/' }
]
})
router.beforeEach((to) => {
const user = useUserStore()
if (to.path === '/login') return user.ready ? '/' : true
if (!user.ready) return '/login'
if (to.name === 'live-home') {
const first = user.firstId && user.entries[user.firstId]
return first
? { name: 'live-menu', params: { menuId: first.id }, query: first.query || {} }
: '/unavailable'
}
if (to.name === 'live-menu') {
const id = String(to.params.menuId)
if (!Object.hasOwn(user.entries, id)) return '/unavailable'
const e = user.entries[id]
to.meta.title = e.title
to.meta.activeMenu = `/nav/${e.id}`
} else if (to.meta.key) {
if (!user.keys.includes(String(to.meta.key))) return '/unavailable'
const parent = Object.values(user.entries).find((e) => e.liveKey === 'members')
if (parent) to.meta.activeMenu = `/nav/${parent.id}`
}
return true
})
export const getRoutePath = (perm: string) =>
perm === 'user.user/detail' && useUserStore().keys.includes('memberDetail')
? '/members/detail'
: ''
export default router
+26
View File
@@ -0,0 +1,26 @@
// No synthetic ledger, arbitrary remote component paths, or workspace-wide dynamic route loader.
export const screens = [
{
key: 'workbench',
path: '/workbench',
component: () => import('@/views/workbench/index.vue')
},
{ key: 'orders', path: '/order', component: () => import('@/views/order/index.vue') },
{
key: 'members',
path: '/members',
component: () => import('@/views/consumer/lists/index.vue')
},
{
key: 'memberDetail',
path: '/members/detail',
hidden: true,
component: () => import('@/views/consumer/lists/detail.vue')
},
{ key: 'roster', path: '/roster', component: () => import('@/views/doctor/roster.vue') },
{
key: 'deptStats',
path: '/dept-stats',
component: () => import('@/views/doctor/dept-tongji.vue')
}
]
+27
View File
@@ -0,0 +1,27 @@
// Only serve local compiled assets. This process has no login route, API proxy, credentials or database access.
import http from 'node:http'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {readFile} from 'node:fs/promises'
const host='127.0.0.1',port=5179,self=`http://${host}:${port}`
const dist=fileURLToPath(new URL('../node_modules/.zyt-live-read/dist/',import.meta.url))
const pages=new Set(['/','/admin','/admin/','/admin/login','/admin/workbench','/admin/order','/admin/members','/admin/members/detail','/admin/roster','/admin/dept-stats','/admin/unavailable'])
const api='https://admin.zhenyangtang.com.cn/adminapi/'
const endpoints=['login/account','auth.admin/mySelf','order.order/orderStats','tcm.diagnosis/assistantDiagnosisStats','order.order/lists','order.order/todayRevenue','tcm.diagnosis/getAssistants','user.user/lists','user.user/detail','auth.admin/lists','doctor.roster/lists','dept.dept/all','doctor.statistics/deptLists']
const mime={'.js':'text/javascript','.css':'text/css','.woff2':'font/woff2','.svg':'image/svg+xml','.png':'image/png','.jpg':'image/jpeg','.webp':'image/webp','.ttf':'font/ttf','.woff':'font/woff'}
const csp=`default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src ${endpoints.map(p=>api+p).join(' ')}; img-src 'self' data: blob:; font-src 'self' data:; form-action 'none'; frame-src 'none'; frame-ancestors 'none'; base-uri 'none'; worker-src 'none'; object-src 'none'`
const entry=path.join(dist,'live-readonly/index.html');await readFile(entry)
http.createServer(async(req,res)=>{
res.setHeader('Content-Security-Policy',csp);res.setHeader('Referrer-Policy','no-referrer');res.setHeader('Cache-Control','no-store');res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('Cross-Origin-Opener-Policy','same-origin');res.setHeader('Permissions-Policy','camera=(), microphone=(), geolocation=()')
const send=(s,t,body)=>{res.writeHead(s,{'Content-Type':t});res.end(req.method==='HEAD'?undefined:body)}
if(req.headers.host!==`${host}:${port}` || (req.headers.origin && req.headers.origin!==self))return send(403,'text/plain','Not allowed')
if(!['GET','HEAD'].includes(req.method))return send(405,'text/plain','Static UI only')
if(!req.url?.startsWith('/') || req.url.startsWith('//'))return send(400,'text/plain','Invalid path')
try {
const {pathname}=new URL(req.url,self)
if(pages.has(pathname) || /^\/admin\/nav\/[A-Za-z0-9_-]+$/.test(pathname))return send(200,'text/html; charset=utf-8',await readFile(entry))
const asset=pathname.match(/^\/admin\/assets\/([a-zA-Z0-9_.-]+)$/)
if(asset && mime[path.extname(asset[1])])return send(200,mime[path.extname(asset[1])],await readFile(path.join(dist,'assets',asset[1])))
}catch { /* Return a non-descriptive 404. No URL, headers or body logging. */ }
send(404,'text/plain','Not found')
}).listen(port,host,()=>console.log(`Local static read-only UI: ${self}/admin/login`))
+168
View File
@@ -0,0 +1,168 @@
// No integration credentials or network. The hardcoded production URL is inspected only in a fetch stub.
import assert from 'node:assert/strict'
import {test, beforeEach, afterEach, mock} from 'node:test'
import request, {clearSession, getSessionMeta, setAllowedResources, OFFICIAL_ORIGIN} from './transport.ts'
const memberList = '/user.user/lists', detail = '/user.user/detail', doctorList = '/auth.admin/lists', rosterList = '/doctor.roster/lists'
const dept = '/doctor.statistics/deptLists', wb = '/order.order/orderStats', orders = '/order.order/lists'
const get = (url,params) => request.get({url,params})
const login = () => request.post({url:'/login/account', params:{account:' example.test ',password:'example?name&value',terminal:1}})
const rows = lists => ({lists, count: lists.length})
const perms = ['*']
const menu = [
['workbench/index','workbench/index'],['consumer/lists/index','user.user/lists'],['consumer/lists/detail','user.user/detail'],
['order/index','order.order/lists'],['doctor/roster','doctor.roster/lists'],['doctor/dept-tongji','doctor.statistics/deptLists']
].map(([component,perms]) => ({component,perms,is_show:1,paths:'page',type:'C'}))
const keys = ['workbench','members','memberDetail','orders','roster','deptStats']
const guards = {is_paw:1, need_bind_work_wechat:false}
const identity = (permissions=perms,root=1) => ({user:{id:23,root,disable:0,name:'测试用户',private_sample:'omit',...guards},permissions,menu})
let stubs, calls
const ok = data => new Response(JSON.stringify({code:1,data}),{headers:{'Content-Type':'application/json'}})
beforeEach(() => {
clearSession()
stubs=[]; calls=[]
mock.method(globalThis,'fetch', async (url,init) => {
calls.push({url,init})
const next=stubs.shift()
if (!next) throw Error('unexpected test request')
return typeof next === 'function' ? await next() : next
})
})
afterEach(() => {clearSession();mock.restoreAll()})
async function enter(profile=identity()) {
stubs.push(ok({token:'test.local.sample',...guards}),ok(profile))
await login()
const result=await get('/auth.admin/mySelf')
setAllowedResources(keys)
return result
}
async function denyWithoutNetwork(action) {
const count=calls.length
await assert.rejects(action)
assert.equal(calls.length,count)
}
test('password is sent once via the fixed HTTPS JSON POST, never in the URL, cookie or returned data',async()=>{
stubs.push(ok({token:'test.local.sample',...guards,other:'secret-field'}))
const result=await login()
assert.deepEqual(result,{authenticated:true,...guards})
const [{url,init}]=calls
assert.equal(url,OFFICIAL_ORIGIN+'/adminapi/login/account')
assert.equal(init.method,'POST')
assert.deepEqual(JSON.parse(init.body),{account:'example.test',password:'example?name&value',terminal:1})
assert.deepEqual([init.credentials,init.cache,init.redirect,init.referrerPolicy,init.mode],['omit','no-store','error','no-referrer','cors'])
assert.equal(init.headers.token,undefined)
assert.deepEqual(getSessionMeta(),{authenticated:true})
setAllowedResources(keys)
await denyWithoutNetwork(()=>get(memberList))
stubs.push(ok(identity()))
await get('/auth.admin/mySelf')
assert.equal(calls[1].init.headers.token,'test.local.sample')
assert.equal(calls[1].init.body,undefined)
await denyWithoutNetwork(()=>get(memberList))
})
test('only projected upstream grants can be selected, plus role-sensitive auxiliary gates',async()=>{
const info=await enter(identity(['order.order/lists','order.order/todayRevenue'],0))
assert.equal(info.user.private_sample,undefined)
for (const path of [memberList,wb,dept,'/dept.dept/all','/order.order/todayRevenue','/tcm.diagnosis/getAssistants']) {
await denyWithoutNetwork(()=>get(path))
}
stubs.push(ok(rows([{id:4,patient:{patient_name:'示例',medical:'unused'},creator:{name:'测试',login_ip:'unused'},pay_qrcode:'unused'}])))
const data=await get(orders,{patient_keyword:'a & b',page_no:1,page_size:1000})
const url=new URL(calls.at(-1).url)
assert.equal(url.searchParams.get('patient_keyword'),'a & b')
assert.equal(url.searchParams.get('page_size'),'100')
assert.equal(data.lists[0].patient.patient_name,'示例')
assert.equal(JSON.stringify(data).includes('unused'),false)
setAllowedResources(['members'])
await denyWithoutNetwork(()=>get(orders))
})
test('literal read whitelist rejects alternate hosts, legacy redirects, exports, mutations, logs and invalid queries before fetch',async()=>{
await enter()
for (const path of ['https://example.invalid/order.order/lists','//example.invalid','/../order.order/lists',
'/order.order/lists?export=2','/adminapi/order.order/lists','/workbench/index','/order.order/pay','/order.order/refund',
'/order.order/syncWechatWorkBills','/order.order/detail','/order.order/export','/order.order/actionLogStats',
'/order.order/actionLogs','/tcm.diagnosis/generateMiniProgramQrcode','/login/workWechatConfig','/auth.admin/bindWorkWechat',
'/auth.admin/detail','/login/changeFirstPassword','/iam/exchange','/login/logout']) {
await denyWithoutNetwork(()=>get(path))
await denyWithoutNetwork(()=>request.post({url:path,params:{}}))
}
for (const q of [{export:1},{export:2},{token:''},{'page_size[]':'10'},{page_size:-1},{page_type:0},{page_no:0},{keyword:['x']},{channel:99}]) {
await denyWithoutNetwork(()=>get(memberList,q))
}
for (const query of [{role_id:2,exclude_disabled:1},{role_id:1},{role_id:1,exclude_disabled:1,apply_data_scope:0}]) {
await denyWithoutNetwork(()=>get(doctorList,query))
}
await denyWithoutNetwork(()=>request.post({url:'/login/account',params:{account:'x',password:'x',terminal:6}}))
})
test('detail ID must occur in this session’s bounded member list, not a caller-supplied route ID',async()=>{
await enter()
await denyWithoutNetwork(()=>get(detail,{id:10}))
stubs.push(ok(rows([{id:10}])),ok({id:10}))
await get(memberList)
assert.equal((await get(detail,{id:10})).id,10)
await denyWithoutNetwork(()=>get(detail,{id:9}))
setAllowedResources(['members'])
await denyWithoutNetwork(()=>get(detail,{id:10}))
setAllowedResources(keys)
await denyWithoutNetwork(()=>get(detail,{id:10}))
await enter()
await denyWithoutNetwork(()=>get(detail,{id:10}))
})
test('doctor dictionary is server scoped, strips IP/phones, rejects non-doctors and binds doctor-week requests',async()=>{
await enter()
const interval={start_date:'2026-05-01',end_date:'2026-05-07'}
await denyWithoutNetwork(()=>get(rosterList,{...interval,doctor_id:51}))
stubs.push(ok(rows([
{id:51,role_id:['1'],disable:0,name:'医生',dept_name:'门诊',phone:'unused'},
{id:52,role_id:[2],disable:0,name:'其他'},
{id:53,role_id:[1],disable:1}
])))
const options=await get(doctorList,{role_id:1,exclude_disabled:1,page_size:1000})
assert.equal(new URL(calls.at(-1).url).searchParams.get('apply_data_scope'),'1')
assert.deepEqual(options.lists,[{id:51,name:'医生',dept_name:'门诊'}])
for (const q of [{...interval,doctor_id:52},{...interval,doctor_id:53},{...interval},{doctor_id:51},
{...interval,doctor_id:51,end_date:'2026-05-08'},{...interval,doctor_id:51,end_date:'2026-04-30'}]) {
await denyWithoutNetwork(()=>get(rosterList,q))
}
stubs.push(ok(rows([])))
await get(rosterList,{...interval,doctor_id:51})
})
test('first-login and WeCom requirements discard tokens, including requirements discovered in mySelf',async()=>{
for(const [change,message] of [[{is_paw:'0'},/改密/],[{need_bind_work_wechat:true},/绑定/]]) {
stubs.push(ok({token:'never-used',...guards,...change}))
await assert.rejects(login,message)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get('/auth.admin/mySelf'))
}
const profile=identity()
profile.user.need_bind_work_wechat=1
stubs.push(ok({token:'ephemeral',...guards}),ok(profile))
await login()
await assert.rejects(()=>get('/auth.admin/mySelf'),/绑定/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get('/auth.admin/mySelf'))
})
test('invalid session response resets all grants, and never propagates server error text or redirect URLs',async()=>{
await enter()
stubs.push(new Response(JSON.stringify({code:2,msg:'secret.example',data:{url:'https://example.invalid'}}),
{headers:{'content-type':'application/json'}}))
await assert.rejects(()=>get(memberList),error=>!String(error).includes('secret.example'))
for (const mode of ['expired','binding','401']) {
await enter()
stubs.push(mode==='401' ? new Response('private error',{status:401}) :
new Response(JSON.stringify({code:mode==='expired'?-1:10}),{headers:{'content-type':'application/json'}}))
await assert.rejects(()=>get(memberList),/(重新登录|企业微信绑定)/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get(memberList))
}
})
test('pending response from a cleared session cannot reestablish credentials or reveal data',async()=>{
let resolve
stubs.push(()=>new Promise(r=>{resolve=r}))
const pending=login()
clearSession()
resolve(ok({token:'stale',...guards}))
await assert.rejects(pending,/会话已结束/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
})
+202
View File
@@ -0,0 +1,202 @@
// This module is imported only by the independent, read-only browser entry point.
import { OFFICIAL_ORIGIN, prepareRequest } from './policy.mjs'
import { projectResources } from './resources.mjs'
export { OFFICIAL_ORIGIN }
type Input = { url: string; params?: Record<string, unknown> }
type SessionMeta = Readonly<{authenticated: boolean}>
let token = ''
let generation = 0
let session = new AbortController()
let verified = false
let root = false
let ceiling = new Set<string>(), allowed = new Set<string>(), permissions = new Set<string>()
const members = new Set<string>(), doctors = new Set<string>()
const CHANGED = '会话已结束,请重新登录。'
const DENIED = '当前账号没有此只读查询权限。'
const OFFLINE = '正式后台未返回可用响应,请检查网络或浏览器跨域授权。'
const REMOTE_ERROR = '正式后台未批准此次查询。'
function resetGrants() {
verified = false
root = false
ceiling.clear()
allowed.clear()
permissions.clear()
members.clear()
doctors.clear()
}
function endSession(announce: boolean) {
const wasActive = Boolean(token)
token = ''
generation++
resetGrants()
session.abort()
session = new AbortController()
if (announce && wasActive && typeof window !== 'undefined') {
window.dispatchEvent(new Event('live-readonly:session-ended'))
}
}
// Even a browser holding the page in its back/forward cache must relinquish the bearer.
if (typeof window !== 'undefined') window.addEventListener('pagehide', () => endSession(false))
export function clearSession() { endSession(true) }
export function getSessionMeta(): SessionMeta { return Object.freeze({authenticated: !!token}) }
// A caller can select fewer routes but cannot grant more than the last mySelf permits.
export function setAllowedResources(keys: Iterable<string>) {
allowed = new Set(verified && token ? [...keys].filter(k => ceiling.has(k)) : [])
if (!allowed.has('members') || !allowed.has('memberDetail')) members.clear()
if (!allowed.has('roster')) doctors.clear()
}
function remember(set: Set<string>, id: unknown) {
if ((typeof id !== 'string' && typeof id !== 'number') || !/^[1-9]\d{0,14}$/.test(String(id))) return
set.add(String(id))
if (set.size > 500) set.delete(set.values().next().value!)
}
function requireSetup(data: any) {
if (String(data?.is_paw) === '0') throw new Error('请先到正式后台完成首次登录改密。')
if (![false, 0, '0'].includes(data?.need_bind_work_wechat)) {
if ([true, 1, '1'].includes(data?.need_bind_work_wechat)) throw new Error('请先到正式后台完成企业微信绑定。')
throw new Error('正式后台未确认账号状态,请在正式后台登录。')
}
if (String(data?.is_paw) !== '1') throw new Error('正式后台未确认账号状态,请在正式后台登录。')
}
function authorize(path: string, resource: string, query: URLSearchParams) {
if (!verified || !allowed.has(resource)) throw new Error(DENIED)
if (resource === 'deptStats' && !root) throw new Error(DENIED)
if (path === '/order.order/todayRevenue' && (!root || !permissions.has('order.order/todayrevenue'))) throw new Error(DENIED)
if (path === '/tcm.diagnosis/getAssistants' && !permissions.has('tcm.diagnosis/getassistants')) throw new Error(DENIED)
if (path === '/user.user/detail' && (!allowed.has('members') || !members.has(query.get('id')!))) {
throw new Error('请从本次登录的用户列表中选择需要查看的用户。')
}
if (path === '/doctor.roster/lists' && !doctors.has(query.get('doctor_id')!)) {
throw new Error('请先从本次登录的可见医生中选择一位医生。')
}
}
async function fetchJson(url: string, init: RequestInit, signal: AbortSignal) {
// Per-request timeout with no transparent retry (in particular, do not replay a login).
const controller = new AbortController()
const stop = () => controller.abort()
signal.addEventListener('abort', stop, {once: true})
const timer = setTimeout(stop, 30000)
try {
const response = await fetch(url, {
...init, signal: controller.signal, mode: 'cors', credentials: 'omit',
cache: 'no-store', redirect: 'error', referrerPolicy: 'no-referrer'
})
if (!response.ok) return {status: response.status, envelope: null}
if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) throw new Error()
return {status: response.status, envelope: await response.json()}
} catch {
throw new Error(signal.aborted ? CHANGED : OFFLINE)
} finally {
clearTimeout(timer)
signal.removeEventListener('abort', stop)
}
}
async function run(method: 'GET' | 'POST', input: Input) {
const path = input?.url
const prepared = prepareRequest(method, path, input?.params)
const login = method === 'POST', identity = path === '/auth.admin/mySelf'
if (login) endSession(false)
else if (!token) throw new Error(CHANGED)
if (identity) {
generation++ // retire any earlier in-flight profile/query from the preceding grant snapshot
resetGrants()
}
const {resource, query, body} = prepared
if (resource) authorize(path, resource, query!)
// path has already matched an exact string in the local allowlist. No caller-supplied
// headers, transform, URL prefix, interceptor, redirect target or RequestInit survives.
const target = new URL('/adminapi' + path, OFFICIAL_ORIGIN)
if (query) target.search = query.toString()
const headers: Record<string,string> = {Accept: 'application/json', version: '1.9.4'}
if (login) headers['Content-Type'] = 'application/json;charset=UTF-8'
else headers.token = token
const gen = generation
try {
const {status, envelope} = await fetchJson(target.href, {method, headers, body}, session.signal)
if (gen !== generation) throw new Error(CHANGED)
if (status === 401 || envelope?.code === -1 || envelope?.code === 10) {
endSession(true)
throw new Error(envelope?.code === 10 ? '请先到正式后台完成企业微信绑定。' : CHANGED)
}
if (status >= 400 || envelope?.code !== 1) {
throw new Error(login ? '登录未成功,请核对账号密码或前往正式后台确认账号状态。' : REMOTE_ERROR)
}
const data = envelope.data
if (login) {
requireSetup(data)
if (typeof data.token !== 'string' || !/^[!-~]{1,4096}$/.test(data.token)) throw new Error('正式后台未返回有效会话。')
token = data.token
// Never forward the login response: it includes the production bearer token.
return {authenticated: true, is_paw: 1, need_bind_work_wechat: false}
}
if (identity) {
requireSetup(data?.user)
if (!/^[1-9]\d{0,14}$/.test(String(data.user.id)) ||
![0,'0',false].includes(data.user.disable) || !Array.isArray(data.menu) || !Array.isArray(data.permissions)) {
throw new Error('正式后台未返回有效的账号权限。')
}
const projected = projectResources(data)
root = data.user.root === 1 || data.user.root === '1'
ceiling = new Set(projected.keys)
permissions = new Set(projected.perms.map((p: string) => p.toLowerCase()))
verified = true
// The store needs the original menu to build routes, not IP, license, contact
// or linked enterprise-account fields from the administrator profile.
const {id, name, root: rootFlag, disable, is_paw, need_bind_work_wechat} = data.user
return {user: {id, name, root: rootFlag, disable, is_paw, need_bind_work_wechat},
menu: data.menu, permissions: data.permissions}
}
// A grant may have been withdrawn while this request was pending.
authorize(path, resource!, query!)
if (path === '/user.user/lists' && Array.isArray(data?.lists) && allowed.has('memberDetail')) {
for (const row of data.lists) remember(members, row?.id)
}
if (path === '/auth.admin/lists') {
// The common administrator API returns IP/phone/signing details, and may not
// apply a SQL role predicate if no doctor exists. Never expose those rows/fields.
const rows = (Array.isArray(data?.lists) ? data.lists : []).filter((r: any) =>
Array.isArray(r?.role_id) && r.role_id.some((id: unknown) => id === 1 || id === '1') &&
(r.disable === 0 || r.disable === '0') && /^[1-9]\d{0,14}$/.test(String(r.id)))
.map((r: any) => ({id: Number(r.id), name: String(r.name || ''), dept_name: String(r.dept_name || '')}))
for (const row of rows) remember(doctors, row.id)
return {lists: rows, count: rows.length}
}
if (path === '/order.order/lists') {
// OrderLists eagerly loads the full patient and creator models. Keep only the
// cells rendered on the approved table, never details or payment material.
if (!Array.isArray(data?.lists)) throw new Error(REMOTE_ERROR)
const lists = data.lists.map((r: any) => {
const {id, order_no, order_type, amount, status, is_exempt, payment_time,
create_time, payment_method, create_type, payee_userid} = r
return {id, order_no, order_type, amount, status, is_exempt, payment_time,
create_time, payment_method, create_type, payee_userid,
patient: r.patient && {patient_name: r.patient.patient_name, phone: r.patient.phone},
creator: r.creator && {name: r.creator.name}, prescription_orders:
(Array.isArray(r.prescription_orders) ? r.prescription_orders : [])
.map((o: any) => ({id: o.id, order_no: o.order_no}))}
})
return {lists, count: data.count, extend: {}}
}
if (path === '/tcm.diagnosis/getAssistants') {
return (Array.isArray(data) ? data : []).map(r => ({id: r.id, name: r.name}))
}
return data
} catch (err) {
if (identity && gen === generation) endSession(true)
throw err
}
}
export default Object.freeze({
get(input: Input, _options?: unknown): Promise<any> { return run('GET', input) },
post(input: Input, _options?: unknown): Promise<any> { return run('POST', input) }
})
+106
View File
@@ -0,0 +1,106 @@
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import request, { clearSession, getSessionMeta, setAllowedResources } from './transport'
import { projectResources } from './resources.mjs'
import { buildNavigation } from './navigation.mjs'
interface MenuNode {
id: string
title: string
icon: string
children?: MenuNode[]
}
interface MenuEntry extends MenuNode {
breadcrumbs: string[]
officialHref: string | null
liveKey: string | null
external?: boolean
query?: Record<string, string>
}
function asSidebar(node: MenuNode, entries: Record<string, MenuEntry>): RouteRecordRaw {
return {
path: `/nav/${node.id}`,
name: node.id,
meta: {
title: node.title,
icon: node.icon,
query: JSON.stringify(entries[node.id]?.query || {})
},
...(node.children?.length
? { children: node.children.map((n) => asSidebar(n, entries)) }
: {})
} as RouteRecordRaw
}
// The sidebar is the account's actual tree. Only the independent capability set can enable API calls.
export default defineStore('liveReadUser', {
state: () => ({
ready: false,
syncing: false,
token: '',
userInfo: {} as Record<string, unknown>,
perms: [] as string[],
keys: [] as string[],
routes: [] as RouteRecordRaw[],
entries: {} as Record<string, MenuEntry>,
firstId: null as string | null,
menuVersion: 0
}),
actions: {
forget() {
this.$reset()
clearSession()
},
async syncMenu() {
if (this.syncing) return
this.syncing = true
try {
const self = await request.get({ url: '/auth.admin/mySelf' })
if (
!getSessionMeta().authenticated ||
!self?.user ||
!/^[1-9]\d*$/.test(String(self.user.id)) ||
![0, '0', false].includes(self.user.disable) ||
String(self.user.is_paw) !== '1' ||
![0, '0', false].includes(self.user.need_bind_work_wechat) ||
!Array.isArray(self.menu) ||
!Array.isArray(self.permissions)
)
throw Error('请先在正式后台完成账号验证。')
const { keys, perms } = projectResources(self)
const nav = buildNavigation(self.menu, keys)
setAllowedResources(keys)
const entries = Object.fromEntries(nav.entries.map((e: MenuEntry) => [e.id, e]))
this.$patch({
userInfo: { name: String(self.user.name || '当前账号') },
perms,
keys,
routes: nav.tree.map((n: MenuNode) => asSidebar(n, entries)),
firstId: nav.firstId,
ready: true,
menuVersion: this.menuVersion + 1
})
// Replace, never merge: revoked menu IDs must disappear on refresh.
this.entries = entries
} catch (e) {
this.forget()
throw e
} finally {
this.syncing = false
}
},
async login(form: { account: string; password: string }) {
this.forget()
try {
await request.post({
url: '/login/account',
params: { account: form.account, password: form.password, terminal: 1 }
})
await this.syncMenu()
return { is_paw: 1, need_bind_work_wechat: false }
} catch (e) {
this.forget()
throw e
}
}
}
})
+432
View File
@@ -0,0 +1,432 @@
<template>
<section class="booking-page" data-testid="booking-ledger">
<header class="booking-heading">
<h1>预约明细</h1>
<p>按接诊日期查询预约,从一条记录查看用户、医生及排班。</p>
</header>
<div class="booking-panel">
<form class="filters" @submit.prevent="search">
<label
>关键词<el-input
v-model="form.keyword"
placeholder="预约号、用户、医生或医助"
clearable
/></label>
<label
>部门<el-select v-model="form.dept_id" placeholder="全部部门" clearable
><el-option
v-for="d in data.departments"
:key="d.dept_id"
:value="String(d.dept_id)"
:label="d.dept_name" /></el-select
></label>
<div class="dates">
<span>接诊日期</span
><el-date-picker
v-model="dates"
type="daterange"
value-format="YYYY-MM-DD"
start-placeholder="开始日期"
end-placeholder="结束日期"
range-separator="至"
/>
</div>
<div class="actions">
<el-button type="primary" native-type="submit">查询</el-button
><el-button @click="reset">重置</el-button>
</div>
</form>
<div v-if="form.patient_id" class="scoped-patient">
当前用户:{{ data.patient_name || '正在读取'
}}<el-button link type="primary" @click="clearPatient">查看全部用户</el-button>
</div>
</div>
<div class="booking-panel results">
<nav class="status-nav" aria-label="按预约状态筛选">
<button
v-for="s in statuses"
:key="s.key"
type="button"
:aria-pressed="status === s.key"
@click="pickStatus(s.key)"
>
{{ s.label }} <b>{{ s.key ? data.summary[s.key] || 0 : data.all }}</b>
</button>
</nav>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-table
:data="data.lists"
v-loading="loading"
empty-text="没有符合条件的预约,请调整筛选条件。"
data-testid="booking-table"
row-key="id"
>
<el-table-column label="接诊日期" min-width="134"
><template #default="{ row }"
><strong>{{ row.date }}</strong
><small>{{ row.time }} · {{ row.visit_type }}</small></template
></el-table-column
>
<el-table-column label="预约号 / 用户" min-width="215"
><template #default="{ row }"
><span>{{ row.patient_name }}</span
><small>{{ row.booking_no }}</small></template
></el-table-column
>
<el-table-column prop="doctor_name" label="接诊医生" min-width="120" />
<el-table-column label="部门 / 医助" min-width="140"
><template #default="{ row }"
>{{ row.dept_name }}<small>{{ row.assistant_name }}</small></template
></el-table-column
>
<el-table-column label="预约状态" min-width="100"
><template #default="{ row }"
><el-tag :type="tagType(row.status)" effect="light">{{
row.status_name
}}</el-tag></template
></el-table-column
>
<el-table-column width="88" label="操作" fixed="right"
><template #default="{ row }"
><el-button type="primary" link @click="open(row)"
>详情</el-button
></template
></el-table-column
>
</el-table>
<footer>
<span data-testid="booking-count">共 {{ data.count }} 条</span
><el-pagination
small
:current-page="page"
:page-size="size"
:total="data.count"
layout="prev, pager, next"
:pager-count="5"
@current-change="go"
/>
</footer>
</div>
<el-drawer v-model="drawer" title="预约详情" size="min(420px, 100%)" append-to-body>
<div v-if="selected" class="booking-details">
<h2>
{{ selected.patient_name }}
<el-tag :type="tagType(selected.status)">{{ selected.status_name }}</el-tag>
</h2>
<p>{{ selected.booking_no }}</p>
<dl>
<dt>预约时刻</dt>
<dd>{{ selected.date }} {{ selected.time }}</dd>
<dt>接诊医生</dt>
<dd>{{ selected.doctor_name }} · {{ selected.visit_type }}</dd>
<dt>排班时段</dt>
<dd>{{ selected.start_time }} – {{ selected.end_time }}</dd>
<dt>归属部门</dt>
<dd>{{ selected.dept_name }}</dd>
<dt>跟进医助</dt>
<dd>{{ selected.assistant_name }}</dd>
</dl>
<div class="related">
<h3>关联记录</h3>
<router-link
:to="{ path: '/members/detail', query: { id: selected.member_id } }"
@click="drawer = false"
>查看用户详情 <span>›</span></router-link
>
<router-link
:to="{
path: '/roster',
query: { doctor_id: selected.doctor_id, date: selected.date }
}"
@click="drawer = false"
>查看该医生当周排班 <span>›</span></router-link
>
<router-link
v-if="selected.patient_order_count"
:to="{ path: '/order', query: { patient_keyword: selected.patient_name } }"
@click="drawer = false"
>查看该用户的订单({{ selected.patient_order_count }})
<span>›</span></router-link
>
</div>
</div>
</el-drawer>
</section>
</template>
<script setup lang="ts" name="PreviewAppointmentLedger">
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
const route = useRoute(),
value = (k: string) => (typeof route.query[k] === 'string' ? (route.query[k] as string) : '')
const statuses = [
{ key: '', label: '全部' },
{ key: 'registered', label: '已挂号' },
{ key: 'completed', label: '已完成' },
{ key: 'canceled', label: '已取消' },
{ key: 'expired', label: '已过号' }
]
const tagKinds = {
registered: 'primary',
completed: 'success',
canceled: 'info',
expired: 'warning'
} as const
const tagType = (s: string) => tagKinds[s as keyof typeof tagKinds] ?? 'info'
type Booking = {
id: number
booking_no: string
date: string
time: string
status: string
status_name: string
visit_type: string
patient_name: string
member_id: number
doctor_id: number
doctor_name: string
dept_name: string
assistant_name: string
start_time: string
end_time: string
patient_order_count: number
}
type Result = {
lists: Booking[]
count: number
all: number
summary: Record<string, number>
departments: { dept_id: number; dept_name: string }[]
patient_name: string
}
const form = reactive({ keyword: '', dept_id: value('dept_id'), patient_id: value('patient_id') }),
dates = ref<string[] | null>(
value('start_date') && value('end_date') ? [value('start_date'), value('end_date')] : null
)
const applied = ref({
...form,
start_date: dates.value?.[0] || '',
end_date: dates.value?.[1] || ''
}),
status = ref(''),
page = ref(1),
size = 15
const data = ref<Result>({
lists: [],
count: 0,
all: 0,
summary: {},
departments: [],
patient_name: ''
}),
selected = ref<Booking>(),
drawer = ref(false),
loading = ref(false),
error = ref('')
let seq = 0
async function load() {
const n = ++seq
loading.value = true
error.value = ''
try {
const result = await request.get({
url: '/local.preview/appointments',
params: { ...applied.value, status: status.value, page_no: page.value, page_size: size }
})
if (n === seq) data.value = result
} catch {
if (n === seq) error.value = '读取本地预约失败,请重新查询。'
} finally {
if (n === seq) loading.value = false
}
}
function go(n: number) {
if (n !== page.value) {
page.value = n
void load()
}
}
function search() {
applied.value = {
...form,
start_date: dates.value?.[0] || '',
end_date: dates.value?.[1] || ''
}
page.value = 1
void load()
}
function reset() {
Object.assign(form, { keyword: '', dept_id: '', patient_id: '' })
dates.value = null
status.value = ''
search()
}
function clearPatient() {
form.patient_id = ''
search()
}
function pickStatus(k: string) {
status.value = k
page.value = 1
void load()
}
function open(row: Booking) {
selected.value = row
drawer.value = true
}
onMounted(load)
</script>
<style scoped>
.booking-page {
min-width: 0;
color: var(--el-text-color-primary);
}
.booking-heading h1 {
font-size: 24px;
font-weight: 650;
margin: 0 0 5px;
}
.booking-heading p,
.booking-details > p {
color: var(--el-text-color-secondary);
font-size: 13px;
margin: 0;
}
.booking-heading {
margin-bottom: 18px;
}
.booking-panel {
background: var(--el-bg-color);
border: 1px solid var(--zyt-card-border, var(--el-border-color-light));
border-radius: 8px;
padding: 18px;
margin-bottom: 16px;
}
.filters {
display: flex;
flex-wrap: wrap;
gap: 14px;
align-items: end;
}
.filters label,
.dates {
display: grid;
gap: 6px;
color: var(--el-text-color-regular);
font-size: 13px;
flex: 1 1 165px;
min-width: 0;
}
.dates {
flex: 1.5 1 265px;
}
.dates :deep(.el-range-editor) {
width: 100%;
min-width: 0;
}
.actions {
display: flex;
}
.scoped-patient {
margin-top: 12px;
font-size: 13px;
}
.scoped-patient button {
margin-left: 10px;
}
.status-nav {
display: flex;
gap: 16px;
overflow-x: auto;
border-bottom: 1px solid var(--el-border-color-lighter);
margin: 0 0 14px;
}
.status-nav button {
background: none;
border: 0;
color: var(--el-text-color-regular);
cursor: pointer;
white-space: nowrap;
padding: 4px 0 10px;
border-bottom: 2px solid transparent;
font: inherit;
font-size: 14px;
}
.status-nav button[aria-pressed='true'] {
color: var(--el-color-primary);
border-color: currentColor;
}
.status-nav b {
font-size: 12px;
font-weight: 500;
}
.results small {
display: block;
color: var(--el-text-color-secondary);
font-size: 12px;
}
.results strong {
font-weight: 550;
}
.results footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 14px;
color: var(--el-text-color-secondary);
font-size: 13px;
}
.booking-details h2 {
font-size: 19px;
display: flex;
align-items: center;
gap: 12px;
margin: 0 0 6px;
}
.booking-details dl {
display: grid;
grid-template-columns: 78px 1fr;
gap: 14px 8px;
padding: 20px 0;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.booking-details dt {
color: var(--el-text-color-secondary);
}
.booking-details dd {
margin: 0;
}
.related h3 {
font-size: 15px;
}
.related a {
display: flex;
align-items: center;
justify-content: space-between;
padding: 11px 0;
color: var(--el-color-primary);
text-decoration: none;
}
.related a:hover {
text-decoration: underline;
}
@media (max-width: 650px) {
.booking-panel {
padding: 12px;
}
.filters {
gap: 10px;
}
.filters label {
flex-basis: 135px;
}
.dates {
flex-basis: 100%;
}
.status-nav {
gap: 12px;
}
}
</style>
+2
View File
@@ -0,0 +1,2 @@
<template><span class="preview-identity" title="仅使用本机生成的演示数据,不连接业务后台"><i aria-hidden="true"></i>本地只读<span>预览</span></span></template>
<style scoped>.preview-identity{display:inline-flex;align-items:center;gap:3px;font-size:12px;color:var(--el-text-color-regular);white-space:nowrap}.preview-identity i{width:7px;height:7px;background:#1b916b;border-radius:50%;margin-right:4px}html[data-admin-ui='v2'] .preview-identity i{background:var(--el-color-primary)}@media(max-width:520px){.preview-identity span{display:none}}</style>
+37
View File
@@ -0,0 +1,37 @@
# 甄养堂管理后台:合成数据演示(5180)
需要查询真实业务数据?请打开 **[正式账号登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [完整后台说明](../live-native/README.md),旧入口不会退回到演示版。
## 单独打开演示版
使用真实后台导航和工作台、订单、用户列表/详情、医生排班、部门统计等业务组件。新增的预约明细是预览专用只读台账,不替代线上接诊、通话或处方流程。独立 HTML、只读预览身份与本机合成数据替代登录、通知轮询和生产账户操作。只允许列明的预览页面;不读业务数据库,无代理,不执行生产发布脚本或同步发布目录。构建复用本项目已安装的前端依赖,不需要后端或数据库凭据。
在 admin 目录执行:
```sh
node local-preview/build.mjs && node local-preview/server.mjs 5180
```
打开 `http://127.0.0.1:5180/admin/workbench`,左栏可访问 6 个入口(另有用户详情页)。初次默认新版,顶栏切换可比较经典版。订单数据是虚构的,可筛选、翻页、看详情,不支持写入。停止前台服务按 Ctrl+C。改代码后重新构建即可,刷新页面获取新版本。
独立构建输出仅在本 worktree 的 `admin/node_modules/.zyt-ui-preview/dist`。本地服务器只绑定 IPv4 回环,校验 Host / Origin;只提供构建静态资源和显式模拟的查询端点(唯一允许的 POST 是查看订单详情)。未识别的请求不会转发。浏览器 CSP 限制接口、静态资源和图片加载。常规生产入口不使用预览路由或合成数据。
只有显式传入 `5180` 才会启动演示服务。旧入口可用 `node local-preview/server.mjs 5178`(或不传参数)启动,不需要构建产物,不加载合成数据;它不会自动启动 5179 或 5180。已有旧入口进程需要由运行方重新启动后才会使用新逻辑。
验证:`node --test local-preview/server.test.mjs local-preview/fixtures.test.mjs local-preview/modules/*.test.mjs` 离线检查入口分流和模拟数据;5180 演示服务运行后 `node local-preview/verify-http.mjs` 复核写入、代理、跨域等均被拒绝。可选的 `browser_smoke.py` 使用 Python Playwright 和本地 Chromium,只允许本机请求。
`verify-art-parameters.py --out <截图目录>` 对照固定的 Art Design Pro 默认参数,测量实际渲染的亮色、暗色和经典外观,并保存对应截图和 computed.json。该验收同样只访问回环地址。
## 本地演示数据如何关联
| 入口 | 可核对的关联 |
| --- | --- |
| `/admin/members` 和 `/admin/members/detail?id=…` | 用户账号与患者档案是不同实体;仅在本地快照内以 ID 关联。详情显示本人预约及已关联订单数量。 |
| `/admin/appointments` | 每条预约引用一个患者、一个排班时段和一位跟进医助;可从抽屉进入用户详情、医生对应周排班或该用户的订单。订单总数按患者统计,不代表该次预约发生了收费。 |
| `/admin/roster` | 前五周、本周、后两周的周排班。有出诊、休息、请假、停诊及无排班的日期。可接诊号源和已占数量分开;取消的预约不占用号源。 |
| `/admin/dept-stats` | 以挂号医助所属部门、接诊日期统计。同部门/日期的「查看明细」带入相同筛选条件。 |
| `/admin/workbench` 和 `/admin/order` | 保留原工作台/订单。订单支持虚构支付状态、未关联患者和操作记录;真实支付、排班变更、调账、导出文件等不开放。 |
日期从本机日历生成,每天第一次读取时建立同一份快照。`browser_modules.py --out <目录>` 在独立浏览器中验证统计下钻、用户/排班/订单跳转、筛选、窄屏及零外部请求。
浏览器验收仅使用 Playwright 配套的 Chromium Headless Shell,不调用系统 Google Chrome。未安装专用引擎时,跳过浏览器验收;不要指定系统浏览器补跑。
+12
View File
@@ -0,0 +1,12 @@
<template><el-config-provider :locale="zhCn"><router-view /></el-config-provider></template>
<script setup lang="ts">
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { useWindowSize } from '@vueuse/core'
import useAppStore from '@/stores/modules/app'
import { useAdminDark } from '@/stores/modules/setting'
import { ScreenEnum } from '@/enums/appEnums'
const app = useAppStore()
useAdminDark()
const { width } = useWindowSize()
watch(width, w => { app.setMobile(w <= ScreenEnum.SM); app.toggleCollapsed(w < ScreenEnum.MD) }, { immediate: true })
</script>
+119
View File
@@ -0,0 +1,119 @@
"""Browser acceptance: real local pages and links agree with the same synthetic graph."""
import argparse, json, re
from pathlib import Path
from urllib.parse import urlsplit, parse_qs
from playwright.sync_api import expect, sync_playwright
p = argparse.ArgumentParser()
p.add_argument('--out', required=True, type=Path)
args = p.parse_args()
args.out.mkdir(exist_ok=True, parents=True)
base = 'http://127.0.0.1:5180'
errors = []
foreign = []
failed = []
passed = []
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, args=['--disable-background-networking', '--no-proxy-server', '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'])
ctx = browser.new_context(viewport={'width': 1440, 'height': 1000}, service_workers='block', color_scheme='light')
pg = ctx.new_page()
pg.set_default_timeout(7000)
ctx.route('**/*', lambda r: r.continue_() if r.request.url.startswith(base + '/') else (foreign.append(r.request.url), r.abort())[1])
pg.on('pageerror', lambda e: errors.append(str(e)))
pg.on('response', lambda r: failed.append([r.status, r.url]) if r.status >= 400 else None)
def go(path):
pg.goto(base + '/admin/' + path, wait_until='networkidle')
def shot(label):
pg.screenshot(path=str(args.out / (label + '.png')))
def param(key):
pg.wait_for_url(re.compile('[?&]' + key + '='))
return parse_qs(urlsplit(pg.url).query)[key][0]
try:
go('dept-stats')
expect(pg.get_by_role('heading', name='部门预约统计')).to_be_visible()
dept = pg.locator('.dept-report-table tbody tr').first
expect(dept).to_be_visible()
n = int(dept.locator('.total-cell').inner_text())
assert n > 0
shot('departments')
dept.get_by_role('link', name='查看明细').click()
expect(pg.get_by_test_id('booking-count')).to_have_text(f'共 {n} 条')
assert param('dept_id') and param('start_date') == param('end_date')
passed.append('部门汇总与下钻明细条数一致')
go('appointments')
first = pg.get_by_test_id('booking-table').locator('tr.el-table__row').first
expect(first).to_be_visible()
shot('appointments')
sample = pg.request.get(base + '/adminapi/local.preview/appointments?page_size=1').json()['data']['lists'][0]
pg.get_by_role('button', name='详情', exact=True).first.click()
drawer = pg.get_by_role('dialog', name='预约详情')
expect(drawer).to_contain_text(sample['booking_no'])
drawer.get_by_role('link', name=re.compile('查看用户详情')).click()
expect(pg.get_by_role('heading', name='用户详情')).to_be_visible()
assert param('id') == str(sample['member_id'])
expect(pg.get_by_role('link', name='查看关联预约')).to_be_visible()
shot('member-detail')
pg.get_by_role('link', name='查看关联预约').click()
assert param('patient_id') == str(sample['patient_id'])
expect(pg.get_by_test_id('booking-ledger')).to_contain_text(sample['patient_name'])
passed.append('预约→用户详情→该用户预约')
pg.get_by_role('button', name='详情', exact=True).first.click()
drawer.get_by_role('link', name=re.compile('当周排班')).click()
assert param('doctor_id') == str(sample['doctor_id'])
expect(pg.get_by_placeholder('搜索医生姓名')).to_have_value(sample['doctor_name'])
expect(pg.get_by_test_id('roster-calendar').locator('tbody tr')).to_have_count(1)
expect(pg.get_by_test_id('roster-calendar')).to_contain_text(sample['start_time'])
passed.append('预约→对应医生及周排班')
go('roster')
rows = pg.get_by_test_id('roster-calendar').locator('tbody tr')
expect(rows).to_have_count(6)
shot('roster')
week = pg.get_by_test_id('roster-week')
old = week.inner_text()
pg.get_by_role('button', name='下一周', exact=True).click()
expect(week).not_to_have_text(old)
pg.get_by_role('button', name='本周', exact=True).click()
expect(week).to_have_text(old)
passed.append('排班六位医生/切周/回本周')
go('members')
expect(pg.get_by_role('heading', name='用户列表')).to_be_visible()
shot('members')
go('appointments')
pg.get_by_role('button', name='详情', exact=True).first.click()
orders = drawer.get_by_role('link', name=re.compile('查看该用户的订单'))
expect(orders).to_be_visible()
orders.click()
expect(pg.get_by_placeholder('患者姓名/手机号')).to_have_value(sample['patient_name'])
expect(pg.locator('.zyt-order-records')).to_contain_text(f"共 {sample['patient_order_count']} 条")
pg.get_by_role('button', name='重置', exact=True).click()
expect(pg.get_by_placeholder('患者姓名/手机号')).to_have_value('')
passed.append('预约→同一用户的订单和数量,可重置为全部')
go('appointments')
pg.get_by_placeholder('预约号、用户、医生或医助').fill('ZZ-NO-APPOINTMENT')
pg.get_by_role('button', name='查询', exact=True).click()
expect(pg.get_by_test_id('booking-count')).to_have_text('共 0 条')
pg.get_by_role('button', name='重置', exact=True).click()
expect(pg.get_by_test_id('booking-count')).not_to_have_text('共 0 条')
pg.get_by_role('button', name=re.compile('已完成')).click()
expect(pg.get_by_test_id('booking-table').locator('tr.el-table__row').first).to_contain_text('已完成')
passed.append('预约状态筛选与空结果')
pg.emulate_media(color_scheme='dark')
expect(pg.locator('html')).to_have_class(re.compile('dark'))
shot('appointments-dark')
pg.set_viewport_size({'width': 390, 'height': 844})
for name in ['appointments', 'roster', 'dept-stats', 'members']:
go(name)
assert pg.evaluate('document.documentElement.scrollWidth<=innerWidth+1'), name + ' overflow'
shot('mobile-' + name)
passed.append('四个模块的手机宽度及深色显示')
assert not (failed or errors or foreign), (failed, errors, foreign)
except Exception:
shot('failure')
print('FAILED AT', pg.url, pg.locator('body').inner_text()[:850], failed, errors, foreign)
raise
finally:
browser.close()
print(json.dumps({'passed': passed, 'external_requests': foreign, 'failed_responses': failed, 'page_errors': errors}, ensure_ascii=False))
+48
View File
@@ -0,0 +1,48 @@
"""Browser acceptance for the loopback-only theme preview; never allow a remote URL."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright, expect
args = argparse.ArgumentParser()
args.add_argument('--screens', type=Path, required=True)
a = args.parse_args(); a.screens.mkdir(exist_ok=True, parents=True)
origin = 'http://127.0.0.1:5180'
errors, external, failed = [], [], []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True, args=['--disable-background-networking','--no-proxy-server','--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'])
ctx = browser.new_context(viewport={'width':1440, 'height':960}, color_scheme='light', service_workers='block')
def only_local(route):
if route.request.url.startswith(origin+'/'):
route.continue_()
else:
external.append(route.request.url); route.abort()
ctx.route('**/*',only_local)
page = ctx.new_page()
page.on('pageerror', lambda e: errors.append(str(e)))
page.on('response', lambda r: failed.append([r.status,r.url]) if r.status >= 400 else None)
page.goto(origin+'/admin/workbench', wait_until='networkidle'); expect(page.get_by_role('heading', name='数据工作台')).to_be_visible()
expect(page.locator('canvas').first).to_be_visible(); assert page.locator('canvas').count() >= 3
root = page.locator('html'); switch = page.locator('[data-admin-ui-toggle]'); expect(root).to_have_attribute('data-admin-ui','v2')
page.screenshot(path=str(a.screens/'workbench.png')); switch.click(); expect(root).to_have_attribute('data-admin-ui','legacy')
page.screenshot(path=str(a.screens/'classic-workbench.png')); switch.click()
page.get_by_role('menuitem',name='订单列表').click(); expect(page.locator('.zyt-order-records tr.el-table__row')).to_have_count(15)
expect(page.get_by_text('共 258 条').first).to_be_visible(); assert page.get_by_role('button',name='创建支付单').count()==0 or not page.get_by_role('button',name='创建支付单').first.is_visible()
rows=page.locator('.zyt-order-records tr.el-table__row'); first=rows.first.locator('td.zyt-order-id').inner_text().strip(); assert first.startswith('DEMO-')
page.screenshot(path=str(a.screens/'orders.png'))
page.locator('.el-pagination .btn-next').first.click(); expect(rows.first.locator('td.zyt-order-id')).not_to_have_text(first)
field=page.get_by_placeholder('请输入订单号'); field.fill(first); page.get_by_role('button',name='查询',exact=True).click(); expect(rows).to_have_count(1)
switch.click(); expect(root).to_have_attribute('data-admin-ui','legacy'); expect(field).to_have_value(first); expect(rows).to_have_count(1)
switch.click(); expect(root).to_have_attribute('data-admin-ui','v2'); expect(field).to_have_value(first)
page.get_by_role('button',name='详情',exact=True).first.click(); dlg=page.get_by_role('dialog',name='订单详情'); expect(dlg).to_be_visible(); expect(dlg).to_contain_text(first); page.keyboard.press('Escape'); expect(dlg).not_to_be_visible()
page.get_by_role('button',name='重置',exact=True).click(); expect(rows).to_have_count(15)
page.emulate_media(color_scheme='dark'); expect(root).to_have_class(re.compile('dark')); page.screenshot(path=str(a.screens/'orders-dark.png'))
page.set_viewport_size({'width':390,'height':844}); page.emulate_media(color_scheme='light'); expect(page.get_by_role('heading',name='订单管理')).to_be_visible()
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), 'page-level horizontal overflow'
expect(switch).to_be_visible(); page.screenshot(path=str(a.screens/'orders-mobile.png'))
browser.close()
assert not errors and not external and not failed, (errors, external, failed)
print(json.dumps({'PASS':['real_workbench_charts','menu_navigation','pagination','filter','switch_preserves_order','read_only_detail','wide_dark_mobile','no_page_overflow'], 'browser_errors':errors,'external_requests':external,'unexpected_http_errors':failed},ensure_ascii=False))
+24
View File
@@ -0,0 +1,24 @@
// Dedicated build: no inherited Vite config, deployment script, production HTML, .env, or public directory.
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { mkdir } from 'node:fs/promises'
import { build } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
const here = path.dirname(fileURLToPath(import.meta.url)), root = path.dirname(here)
process.chdir(root)
export const outDir = path.join(root,'node_modules/.zyt-ui-preview/dist')
await mkdir(outDir, {recursive:true})
await build({ root, mode:'local-preview', configFile:false, envFile:false, envPrefix:'ZYT_LOCAL_NO_EXPOSE_', publicDir:false, base:'/admin/',
cacheDir:path.join(root,'node_modules/.zyt-ui-preview/cache'),
define:{'import.meta.env.VITE_APP_BASE_URL':JSON.stringify('')},
resolve:{alias:[{find:/^@\/router$/,replacement:path.join(here,'router.ts')},{find:/^\.\/user-drop-down\.vue$/,replacement:path.join(here,'PreviewIdentity.vue')},{find:'@',replacement:path.join(root,'src')}]},
plugins:[vue(),vueJsx(),createSvgIconsPlugin({iconDirs:[path.join(root,'src/assets/icons')],symbolId:'local-icon-[dir]-[name]'}),AutoImport({imports:['vue','vue-router'],resolvers:[ElementPlusResolver({importStyle:false})],dts:false}),Components({dirs:[path.join(root,'src/components')],directoryAsNamespace:true,dts:false}),vueSetupExtend()],
build:{outDir,emptyOutDir:true,sourcemap:false,reportCompressedSize:false,rollupOptions:{input:path.join(here,'index.html')}},
css:{preprocessorOptions:{scss:{api:'modern-compiler'}}}
})
+220
View File
@@ -0,0 +1,220 @@
import { makeRosterSnapshot, resolveRoster } from './modules/roster.mjs'
import { makeAppointments, resolveAppointments } from './modules/appointments.mjs'
import { resolveDeptStats } from './modules/dept-stats.mjs'
import { memberIdForPatient, resolvePeople } from './modules/people.mjs'
// Local Vite preview only. All records are generated here; no accounts, DBs or upstream APIs.
const departments = ['一组', '二组', '三组'].map((n, i) => ({ dept_id: i + 1, dept_name: '演示运营' + n }))
const assistants = ['宁禾', '云初', '林川', '叶青', '许安'].map((n, i) => ({
id: 101 + i, name: n + '(演示)', dept_id: departments[i % departments.length].dept_id
}))
const types = ['退款统计', '挂号费', '问诊费', '药品费用', '首付费用', '尾款费用', '其他费用', '全部费用', '驼奶费用']
const amounts = [29, 99, 238, 300, 580, 68, 798, 199]
// Never use dialable numbers or real patient data in the preview.
const patients = Array.from({ length: 48 }, (_, i) => ({
id: 501 + i, patient_name: '演示患者' + pad(i + 1), phone: '000****' + String(1000 + i)
}))
function pad(n) { return String(n).padStart(2, '0') }
function dateLabel(offset = 0, now = new Date()) {
const d = new Date(now)
d.setDate(d.getDate() - offset)
return [d.getFullYear(), pad(d.getMonth() + 1), pad(d.getDate())].join('-')
}
function makeOrders(now) {
const rows = []
const states = [2, 1, 5, 2, 4, 3, 2, 2, 1, 2, 3, 2, 5, 2, 4, 2, 2]
const channels = ['normal', 'wechat_work', 'normal', 'express_cod', 'fubei']
for (let day = 0; day < 30; day++) {
const date = dateLabel(day, now)
const count = day ? 5 + day % 7 : 28
// Spread today's orders over *elapsed* time, not later this afternoon.
const latestMinute = day ? 17 * 60 : now.getHours() * 60 + now.getMinutes()
for (let slot = 0; slot < count; slot++) {
const i = rows.length
const minute = Math.max(0, latestMinute - slot * 13)
const time = date + ' ' + pad(Math.floor(minute / 60)) + ':' + pad(minute % 60) + ':00'
const type = i % 8 + 1
const status = states[i % states.length]
const creator = assistants[(i + Math.floor(i / 8)) % assistants.length]
const patient = i % 6 === 1 ? null : patients[i % patients.length]
const channel = status === 5 ? 'fubei' : channels[i % channels.length]
rows.push({
id: 10001 + i, order_no: 'DEMO-' + date.replaceAll('-', '') + '-' + String(i + 1).padStart(4, '0'),
creator_id: creator.id, creator, patient_id: patient?.id || 0, patient,
amount: (amounts[type - 1] + i % 3).toFixed(2),
status, order_type: type, create_type: channel, is_exempt: 0,
payment_method: channel === 'normal' ? (i % 2 ? 'alipay' : 'wechat') : channel,
create_time: time, payment_time: [2, 4].includes(status) ? time : null,
remark: '本地合成的支付单,用于预览界面。',
prescription_orders: patient && i % 3 === 0 ? [{ id: 20001 + i, order_no: 'DEMO-RX-' + (301 + i) }] : []
})
}
}
return rows
}
function positiveInt(raw, fallback, maximum) {
const n = Number(raw)
return Number.isSafeInteger(n) && n > 0 ? Math.min(n, maximum) : fallback
}
function paged(rows, q) {
const page = positiveInt(q.page_no, 1, Number.MAX_SAFE_INTEGER)
const size = positiveInt(q.page_size, 15, 100)
return { count: rows.length, lists: rows.slice((page - 1) * size, page * size), extend: {} }
}
function matchesPatient(p, keyword) {
return !keyword || (p && (p.patient_name.includes(keyword) || p.phone.includes(keyword)))
}
function filterOrders(rows, q) {
const end = endOfFilter(q.create_time_end)
return rows.filter(r =>
(!q.order_no || r.order_no.toLowerCase().includes(String(q.order_no).trim().toLowerCase())) &&
matchesPatient(r.patient, String(q.patient_keyword ?? '').trim()) &&
(!q.assistant_id || r.creator_id === Number(q.assistant_id)) &&
(!q.order_type || r.order_type === Number(q.order_type)) &&
(!q.status || r.status === Number(q.status)) &&
(!q.patient_association || (r.patient ? 'associated' : 'pending') === q.patient_association) &&
(!q.create_time_start || r.create_time >= q.create_time_start) &&
(!end || r.create_time <= end)
)
}
function endOfFilter(s) {
return s && s.length === 10 ? s + ' 23:59:59' : s
}
function sumMoney(rows) {
return (rows.reduce((sum, r) => sum + Math.round(Number(r.amount) * 100), 0) / 100).toFixed(2)
}
function rankOrders(rows) {
return assistants.map(a => {
const own = rows.filter(r => r.creator_id === a.id)
return { ...a, count: own.length, amount: sumMoney(own) }
}).filter(a => a.count).sort((a, b) => b.count - a.count || Number(b.amount) - Number(a.amount))
}
function chart(ranking, name) {
return { xAxis: ranking.map(a => a.name), series: [{ name, data: ranking.map(a => a.count) }] }
}
function orderStats(rows, q, now) {
const today = dateLabel(0, now)
const start = dateLabel(Math.min(30, Math.max(0, Number(q.days ?? 0) || 0)), now)
const type = Number(q.order_type ?? -1)
const selected = rows.filter(r => r.create_time >= start &&
(type === 0 ? r.status === 4 : r.status === 2 && (type === -1 || r.order_type === type)))
const current = selected.filter(r => r.create_time.startsWith(today))
const ranking = rankOrders(selected)
return {
order_type_name: type === -1 ? '全部(已支付)' : types[type], date_range: [start, today],
today_total: current.length, today_amount: sumMoney(current), today_ranking: rankOrders(current),
ranking, chart: chart(ranking, '单数'),
departments: departments.map(d => {
const own = selected.filter(r => r.creator.dept_id === d.dept_id)
return { ...d, total: own.length, amount: sumMoney(own), members: rankOrders(own) }
})
}
}
function diagnosisStats(q, now) {
const days = Math.min(30, Math.max(0, Math.trunc(Number(q.days ?? 0) || 0)))
const rank = (daysBack) => assistants.map((a, i) => {
let count = 0
for (let day = 0; day <= daysBack; day++) count += 2 + (2 * i + day) % 7
return { ...a, count }
}).sort((a, b) => b.count - a.count)
const today = rank(0), ranking = rank(days)
return {
date_range: [dateLabel(days, now), dateLabel(0, now)], today_ranking: today,
today_total: today.reduce((n, a) => n + a.count, 0), ranking, chart: chart(ranking, '诊单数'),
departments: departments.map(d => {
const members = ranking.filter(a => a.dept_id === d.dept_id)
return { ...d, total: members.reduce((n, a) => n + a.count, 0), assistants: members }
})
}
}
function workbench(rows, now) {
// The actual Vue component reverses dates (but NOT values) on receipt.
const date = Array.from({ length: 7 }, (_, i) => dateLabel(i, now))
const sale = [...date].reverse().map(d => Number(
(Number(sumMoney(rows.filter(r => r.status === 2 && r.payment_time.startsWith(d)))) / 10000).toFixed(2)
))
return { menu: [], today: {}, version: {}, support: {},
visitor: { date, list: [{ data: [68, 83, 79, 105, 90, 120, 111] }] },
sale: { date: [...date], list: [{ data: sale }] } }
}
function logs(rows) {
return rows.map(r => ({
order_id: r.id, admin_id: r.creator_id, admin_name: r.creator.name, action_label: '创建支付单',
summary: '生成本地演示记录', create_time_text: r.create_time
}))
}
// Keep timestamps stable while browsing, and reseed the sample automatically on a new local day.
let sampleClock
function snapshotTime() {
const live = new Date()
if (!sampleClock || dateLabel(0, sampleClock) !== dateLabel(0, live)) sampleClock = live
return sampleClock
}
let activeSnapshot
// All new modules share one day-stable object graph; no unrelated fake totals per page.
export function createPreviewSnapshot(now = snapshotTime()) {
const { doctors, slots } = makeRosterSnapshot(departments, now)
const data = { now, departments, assistants, patients, doctors, slots, orders: makeOrders(now) }
return { ...data, appointments: makeAppointments(data) }
}
function currentSnapshot() {
const clock = snapshotTime()
if (activeSnapshot?.now !== clock) activeSnapshot = createPreviewSnapshot(clock)
return activeSnapshot
}
/** Closed allowlist; null means the transport must reject, never proxy. */
export function resolveFixture(pathname, params = {}) {
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
const snapshot = currentSnapshot()
const { now, orders } = snapshot
const ok = data => ({ code: 1, data, msg: '', show: 0 })
switch (pathname) {
case '/adminapi/workbench/index': return ok(workbench(orders, now))
case '/adminapi/tcm.diagnosis/assistantDiagnosisStats': return ok(diagnosisStats(q, now))
case '/adminapi/order.order/orderStats': return ok(orderStats(orders, q, now))
case '/adminapi/order.order/lists': return ok(paged(filterOrders(orders, q), q))
case '/adminapi/order.order/todayRevenue': {
const paid = orders.filter(r => r.status === 2 && r.payment_time.startsWith(dateLabel(0, now)))
return ok({ count: paid.length, amount: sumMoney(paid) })
}
case '/adminapi/tcm.diagnosis/getAssistants': return ok(assistants.map(a => ({
id: a.id, name: a.name, dept_ids: [a.dept_id], dept_names: departments[a.dept_id - 1].dept_name
})))
case '/adminapi/tcm.diagnosis/searchPatient':
return ok(paged(patients.filter(p => matchesPatient(p, String(q.keyword ?? '').trim())), q))
// The shared export widget asks for counts even when its button is hidden.
// Only answer the metadata probe. Never generate/download an export (mode 2).
case '/adminapi/order.order/export': {
if (String(q.export) !== '1') return null
const count = filterOrders(orders, q).length
const size = positiveInt(q.page_size, 15, 100)
return ok({ count, sum_page: Math.ceil(count / size), page_size: size, max_page: 0, all_max_size: 0 })
}
case '/adminapi/order.order/detail': {
const row = orders.find(r => r.id === Number(q.id))
return row ? ok(row) : { code: 0, data: null, show: 1, msg: '演示订单不存在' }
}
case '/adminapi/order.order/actionLogs':
return ok(paged(logs(orders.filter(r => r.id === Number(q.order_id))), q))
case '/adminapi/order.order/actionLogStats': {
const start = q.start_time || dateLabel(6, now), end = endOfFilter(q.end_time || dateLabel(0, now))
const records = logs(orders).filter(l => l.create_time_text >= start && l.create_time_text <= end)
return ok({ start_time: start, end_time: end, list: assistants.map(a => ({
admin_name: a.name, cnt: records.filter(r => r.admin_id === a.id).length
})).filter(a => a.cnt).sort((a, b) => b.cnt - a.cnt).slice(0, positiveInt(q.limit, 50, 100)) })
}
default: return resolvePeople(pathname, q, snapshot) ?? resolveRoster(pathname, q, snapshot) ??
resolveDeptStats(pathname, q, snapshot) ?? resolveAppointments(pathname, q, snapshot, memberIdForPatient)
}
}
+80
View File
@@ -0,0 +1,80 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { resolveFixture } from './fixtures.mjs'
const read = (path, query) => {
const result = resolveFixture('/adminapi/' + path, query)
assert.equal(result.code, 1)
assert.deepEqual([result.msg, result.show], ['', 0])
return result.data
}
const orders = q => read('order.order/lists', q)
test('分页、每种状态、订单号、患者与医助过滤使用同一数据集', () => {
const first = orders({}), second = orders(new URLSearchParams('page_no=2&page_size=15'))
assert.ok(first.count > 15)
assert.equal(first.lists.length, 15)
assert.equal(second.count, first.count)
assert.ok(!first.lists.some(r => second.lists.some(other => other.id === r.id)))
assert.deepEqual(orders({ order_no: 'NO-MATCH' }).lists, [])
for (const status of [1, 2, 3, 4, 5]) {
const { lists } = orders({ status: String(status) })
assert.ok(lists.length && lists.every(r => r.status === status))
}
const r = first.lists[0]
assert.deepEqual(orders({ order_no: r.order_no.toLowerCase(), patient_keyword: r.patient.phone,
order_type: r.order_type, assistant_id: r.creator.id, status: r.status, create_time_start: r.create_time,
create_time_end: r.create_time }).lists, [r])
assert.equal(orders({ create_time_end: '2000-01-01' }).count, 0)
assert.equal(orders({ patient_association: 'pending' }).count + orders({ patient_association: 'associated' }).count, first.count)
assert.ok(orders({ patient_association: 'pending' }).lists.every(r => !r.patient))
assert.ok(read('tcm.diagnosis/getAssistants').some(a => a.id === r.creator_id))
assert.ok(read('tcm.diagnosis/searchPatient', { keyword: r.patient.patient_name }).lists.some(p => p.id === r.patient_id))
})
test('订单详情和日志只读取演示数据,统计按日期返回', () => {
const sample = orders({}).lists[0]
assert.deepEqual(read('order.order/detail', { id: sample.id }), sample)
assert.equal(resolveFixture('/adminapi/order.order/detail', { id: -1 }).code, 0)
const records = read('order.order/actionLogs', { order_id: sample.id })
assert.ok(records.count && records.lists.every(l => l.order_id === sample.id))
assert.ok(read('order.order/actionLogStats').list.length)
assert.deepEqual(read('order.order/actionLogStats', { start_time: '1999-01-01', end_time: '1999-01-07' }).list, [])
})
test('工作台图表均有数据;今日收益、类型、周期和排行榜可核对', () => {
const revenue = read('order.order/todayRevenue')
const today = read('order.order/orderStats', { order_type: -1, days: 0 })
assert.deepEqual([revenue.count, revenue.amount], [today.today_total, today.today_amount])
assert.ok(revenue.count && Number(revenue.amount) > 0)
const count = rs => rs.reduce((n, a) => n + a.count, 0)
assert.equal(count(today.ranking), revenue.count)
const week = read('order.order/orderStats', { order_type: -1, days: 7 })
assert.ok(count(week.ranking) > revenue.count)
assert.ok(week.chart.xAxis.length && week.departments.every(d => d.total > 0))
for (let type = 0; type <= 8; type++) {
const result = read('order.order/orderStats', { order_type: type, days: 30 })
assert.ok(result.order_type_name && result.ranking.length)
}
const diagnosis = read('tcm.diagnosis/assistantDiagnosisStats', { days: 14 })
assert.equal(diagnosis.today_total, count(diagnosis.today_ranking))
assert.ok(diagnosis.chart.xAxis.length && count(diagnosis.ranking) > diagnosis.today_total)
const wb = read('workbench/index')
for (const series of [wb.visitor, wb.sale]) {
assert.equal(series.date.length, series.list[0].data.length)
assert.ok(series.list[0].data.every(n => n > 0))
}
})
test('未列入白名单的路径一律不生成响应(包括会写入的 GET)', () => {
for (const p of ['order.order/create', 'order.order/delete', 'order.order/edit', 'order.order/syncWechatWorkBills',
'order.order/syncWechatWorkBillsDebug', 'order.order/export', 'order.order/pay', 'unknown']) {
assert.equal(resolveFixture('/adminapi/' + p), null)
}
assert.equal(resolveFixture('/api/workbench/index'), null)
})
test('隐藏导出控件只获得合成条数,不生成导出文件', () => {
assert.equal(read('order.order/export', { export: '1' }).count, orders({}).count)
assert.equal(resolveFixture('/adminapi/order.order/export', { export: '2' }), null)
})
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh-CN" data-admin-ui="v2"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>甄养堂 · 本地主题预览</title><link rel="icon" href="data:,"></head><body><div id="app"></div><script type="module" src="./main.ts"></script></body></html>
+27
View File
@@ -0,0 +1,27 @@
import 'virtual:svg-icons-register'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import '@/styles/index.scss'
import '@/install/plugins/echart'
import { createApp, watch } from 'vue'
import ElementPlus from 'element-plus'
import installIcons from '@/install/plugins/element'
import perms from '@/install/directives/perms'
import store from '@/stores'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import useTabsStore from '@/stores/modules/multipleTabs'
import useSettingStore from '@/stores/modules/setting'
import Root from './Root.vue'
import router, { pages } from './router'
import classicLogo from './preview-mark.svg'
import artLogo from './preview-mark-art.svg'
const app = createApp(Root)
app.use(store); app.use(ElementPlus); installIcons(app); app.directive('perms', perms)
useUserStore().$patch({ token: '', userInfo: { name: '本地预览', role_ids: [] }, perms: ['order.order/lists','order.order/detail','user.user/lists','user.user/detail'], routes: pages.map(({ path, name, meta }) => ({ path, name, meta })) as any })
const appState = useAppStore(), settings = useSettingStore()
appState.$patch({ configFetchAttempted: true, config: { web_name: '甄养堂' } })
settings.$patch({ showLogo: true })
watch(() => settings.adminUi, mode => { appState.config.web_logo = mode === 'v2' ? artLogo : classicLogo }, { immediate: true })
useTabsStore().setRouteName('preview-workbench')
app.use(router); router.isReady().then(() => app.mount('#app'))
@@ -0,0 +1,145 @@
// Local, synthetic scheduling ledger. No transport, database or business writes.
// IDs are deterministic for a calendar slot; appointment status is evaluated at snapshot time.
const statusNames = {
registered: '已挂号',
completed: '已完成',
canceled: '已取消',
expired: '已过号'
}
const pad = (n) => String(n).padStart(2, '0')
const iso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
const minuteOf = (s) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3, 5))
const asTime = (m) => `${pad(Math.floor(m / 60))}:${pad(m % 60)}`
export function makeAppointments({ doctors, slots, patients, assistants, now }) {
const rows = [],
occupied = new Set(),
today = iso(now),
minute = now.getHours() * 60 + now.getMinutes()
const byDoctor = new Map(doctors.map((d) => [d.id, d]))
for (const slot of slots) {
if (slot.status !== 1) continue
const doc = byDoctor.get(slot.doctor_id),
team = assistants.filter((a) => a.dept_id === doc.dept_id)
const capacity = Math.min(
slot.quota || Infinity,
Math.floor((minuteOf(slot.end_time) - minuteOf(slot.start_time)) / slot.slot_minutes)
)
const n = Math.min(capacity, 2 + ((slot.id + doc.id) % 7))
for (let i = 0; i < n; i++) {
const id = slot.id * 16 + i,
start = minuteOf(slot.start_time) + i * slot.slot_minutes
const future = slot.date > today || (slot.date === today && start >= minute)
const status =
id % 11 === 0
? 'canceled'
: future
? 'registered'
: id % 9 === 0
? 'expired'
: 'completed'
let pi = (Math.floor(slot.id / 100) + doc.id * 7 + i * 5) % patients.length
const occupiedKey = (p) => `${slot.date}/${start}/${p.id}`
for (let j = 0; j < patients.length && occupied.has(occupiedKey(patients[pi])); j++)
pi = (pi + 1) % patients.length
const patient = patients[pi]
if (status !== 'canceled') {
if (occupied.has(occupiedKey(patient))) continue
occupied.add(occupiedKey(patient))
slot.booked_count++
}
rows.push({
id,
booking_no: `YY-${slot.date.replaceAll('-', '')}-${doc.id}-${pad(Math.floor(start / slot.slot_minutes))}`,
slot_id: slot.id,
doctor_id: doc.id,
dept_id: doc.dept_id,
assistant_id: team[(i + doc.id) % team.length].id,
patient_id: patient.id,
date: slot.date,
time: asTime(start),
status,
visit_type: i % 3 ? '复诊' : '初诊'
})
}
}
return rows
}
export function resolveAppointments(pathname, q, snapshot, memberIdForPatient) {
if (pathname !== '/adminapi/local.preview/appointments' || q.export != null) return null
const { appointments, departments, doctors, assistants, patients, slots, orders, now } =
snapshot
const map = (a, id = 'id') => new Map(a.map((v) => [v[id], v]))
const [ds, dr, as, ps, ss] = [
map(departments, 'dept_id'),
map(doctors),
map(assistants),
map(patients),
map(slots)
]
const counts = new Map()
for (const o of orders)
if (o.patient_id) counts.set(o.patient_id, 1 + (counts.get(o.patient_id) || 0))
const kw = String(q.keyword || '')
.trim()
.toLowerCase(),
today = iso(now)
let matches = appointments.filter(
(a) =>
(!q.dept_id || a.dept_id === Number(q.dept_id)) &&
(!q.patient_id || a.patient_id === Number(q.patient_id)) &&
(!q.start_date || a.date >= q.start_date) &&
(!q.end_date || a.date <= q.end_date) &&
(!kw ||
[
a.booking_no,
ps.get(a.patient_id).patient_name,
dr.get(a.doctor_id).name,
as.get(a.assistant_id).name
].some((s) => s.toLowerCase().includes(kw)))
)
const all = matches.length,
summary = Object.fromEntries(
Object.keys(statusNames).map((s) => [s, matches.filter((r) => r.status === s).length])
)
if (q.status) matches = matches.filter((a) => a.status === q.status)
// Today's bookings first, then upcoming earliest first, then history most recent first.
const group = (a) => (a.date === today ? 0 : a.date > today ? 1 : 2)
matches.sort(
(a, b) =>
group(a) - group(b) ||
(group(a) === 2 ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date)) ||
a.time.localeCompare(b.time) ||
a.id - b.id
)
const size = Math.min(100, Math.max(1, parseInt(q.page_size, 10) || 15)),
page = Math.max(1, parseInt(q.page_no, 10) || 1)
const lists = matches
.slice((page - 1) * size, page * size)
.map((a) => ({
...a,
member_id: memberIdForPatient(a.patient_id),
patient_name: ps.get(a.patient_id).patient_name,
doctor_name: dr.get(a.doctor_id).name,
dept_name: ds.get(a.dept_id).dept_name,
assistant_name: as.get(a.assistant_id).name,
status_name: statusNames[a.status],
start_time: ss.get(a.slot_id).start_time,
end_time: ss.get(a.slot_id).end_time,
patient_order_count: counts.get(a.patient_id) || 0
}))
return {
code: 1,
data: {
lists,
count: matches.length,
all,
summary,
departments,
today,
patient_name: ps.get(Number(q.patient_id))?.patient_name || ''
},
show: 0,
msg: ''
}
}
@@ -0,0 +1,91 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPreviewSnapshot } from '../fixtures.mjs'
import { memberIdForPatient, resolvePeople } from './people.mjs'
import { resolveDeptStats } from './dept-stats.mjs'
import { resolveAppointments } from './appointments.mjs'
const snap = (d) => createPreviewSnapshot(new Date(d))
const bookings = (s, q = {}) =>
resolveAppointments('/adminapi/local.preview/appointments', q, s, memberIdForPatient).data
for (const local of ['2026-12-01T10:00:00', '2027-01-01T08:00:00', '2028-02-29T22:00:00']) {
test(`关联完整、排班容量和唯一性:${local}`, () => {
const s = snap(local),
slots = new Map(s.slots.map((v) => [v.id, v])),
occupied = new Map(),
times = new Set(),
nos = new Set()
for (const b of s.appointments) {
const sl = slots.get(b.slot_id),
d = s.doctors.find((v) => v.id === b.doctor_id),
a = s.assistants.find((v) => v.id === b.assistant_id)
assert.ok(sl && d && a && s.patients.some((v) => v.id === b.patient_id))
assert.equal(d.dept_id, a.dept_id)
assert.equal(b.dept_id, a.dept_id)
assert.equal(b.date, sl.date)
assert.equal(sl.status, 1)
assert.equal(sl.doctor_id, d.id)
assert.ok(sl.start_time <= b.time && b.time < sl.end_time)
assert.ok(!nos.has(b.booking_no))
nos.add(b.booking_no)
if (b.status !== 'canceled') {
const key = [b.patient_id, b.date, b.time].join('/')
assert.ok(!times.has(key))
times.add(key)
occupied.set(sl.id, 1 + (occupied.get(sl.id) || 0))
}
}
const min = (t) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
for (const v of s.slots) {
assert.equal(v.booked_count, occupied.get(v.id) || 0)
assert.ok(
v.booked_count <=
Math.min(
v.quota || Infinity,
(min(v.end_time) - min(v.start_time)) / v.slot_minutes
)
)
}
assert.deepEqual(
new Set(s.appointments.map((v) => v.status)),
new Set(['registered', 'completed', 'expired', 'canceled'])
)
})
}
test('三个统计周期按部门下钻;状态分布与明细精确一致', () => {
const s = snap('2026-12-01T14:30:00')
for (const time_type of ['today', 'week', 'month']) {
const stats = resolveDeptStats('/adminapi/doctor.statistics/deptLists', { time_type }, s)
.data.lists
assert.ok(stats.length)
for (const r of stats) {
const data = bookings(s, {
dept_id: r.dept_id,
start_date: r.start_date,
end_date: r.end_date
})
assert.equal(data.all, r.total_count)
for (const [k, n] of Object.entries(data.summary)) assert.equal(n, r[k + '_count'])
}
}
})
test('预约、账号、订单同人关联;按预约号检索与分页一致', () => {
const s = snap('2026-12-01T14:30:00'),
one = bookings(s).lists[0]
const person = resolvePeople('/adminapi/user.user/detail', { id: one.member_id }, s).data
assert.equal(person.patient_id, one.patient_id)
assert.equal(bookings(s, { patient_id: one.patient_id }).count, person.appointment_count)
assert.equal(person.order_count, one.patient_order_count)
assert.equal(bookings(s, { keyword: one.booking_no }).count, 1)
assert.equal(bookings(s, { keyword: '某条不存在的演示预约' }).count, 0)
const next = bookings(s, { page_no: 2 }).lists
assert.ok(next.every((b) => !bookings(s).lists.some((r) => b.id === r.id)))
assert.equal(
resolveAppointments(
'/adminapi/local.preview/appointments',
{ export: 2 },
s,
memberIdForPatient
),
null
)
})
@@ -0,0 +1,47 @@
// Mirrors StatisticsLists::getDeptStatistics; this module reads only the provided local snapshot.
const ok = data => ({ code: 1, data, show: 0, msg: '' })
function dateAt(now, offset) {
const date = new Date(now)
date.setDate(date.getDate() + offset)
return [date.getFullYear(), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0')].join('-')
}
function period(q, now) {
const end = dateAt(now, 0)
if (q.time_type === 'custom' && q.start_date && q.end_date) {
return [q.start_date, q.end_date, `自定义 (${q.start_date} 至 ${q.end_date})`]
}
if (q.time_type === 'week' || q.time_type === 'month') {
const days = q.time_type === 'week' ? 7 : 30
const start = dateAt(now, 1 - days)
return [start, end, `最近${days}天 (${start} 至 ${end})`]
}
return [end, end, `今天 (${end})`]
}
export function resolveDeptStats(pathname, params, snapshot) {
if (pathname === '/adminapi/dept.dept/all') {
return ok(snapshot.departments.map(d => ({ id: d.dept_id, name: d.dept_name, children: [] })))
}
if (pathname !== '/adminapi/doctor.statistics/deptLists') return null
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
const [start_date, end_date, time_range] = period(q, snapshot.now)
const assistants = new Map(snapshot.assistants.map(a => [a.id, a.dept_id]))
const groups = new Map(snapshot.departments.filter(d => !q.dept_id || d.dept_id === Number(q.dept_id)).map(d => [d.dept_id, {
dept_id: d.dept_id, dept_name: d.dept_name, total_count: 0, registered_count: 0, completed_count: 0,
canceled_count: 0, expired_count: 0, completion_rate: 0, start_date, end_date, time_range
}]))
for (const a of snapshot.appointments) {
if (a.date < start_date || a.date > end_date) continue
const row = groups.get(assistants.get(a.assistant_id))
if (!row) continue
row.total_count += 1
// Total is COUNT(*) on the server; the four named statuses get separate subtotals.
if (['registered', 'completed', 'canceled', 'expired'].includes(a.status)) row[a.status + '_count'] += 1
}
// SQL GROUP BY does not manufacture zero-count rows when a department has no activity.
const lists = [...groups.values()].filter(r => r.total_count)
for (const row of lists) row.completion_rate = Number((100 * row.completed_count / row.total_count).toFixed(2))
return ok({ lists, count: lists.length, page_no: Number(q.page_no) || 1, page_size: Number(q.page_size) || 15, extend: [] })
}
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { resolveDeptStats } from './dept-stats.mjs'
const snapshot = {
now: new Date(2026, 2, 1, 1, 0),
departments: [{ dept_id: 1, dept_name: '演示一组' }, { dept_id: 2, dept_name: '演示二组' }, { dept_id: 3, dept_name: '无预约组' }],
assistants: [{ id: 101, dept_id: 1 }, { id: 102, dept_id: 2 }],
// Deliberately different from the assistant: StatisticsLists groups by assistant, not doctor.
doctors: [{ id: 401, dept_id: 2 }], patients: [], slots: [],
appointments: [
['2026-03-01', 'completed', 101], ['2026-03-01', 'registered', 101], ['2026-03-01', 'expired', 101],
['2026-03-01', 'canceled', 102], ['2026-02-23', 'completed', 101], ['2026-02-22', 'canceled', 102],
['2026-01-31', 'completed', 102], ['2026-01-30', 'registered', 101], ['2026-03-02', 'registered', 102],
['2026-03-01', 'completed', 999]
].map(([date, status, assistant_id], i) => ({ id: i + 1, doctor_id: 401, date, status, assistant_id }))
}
const path = '/adminapi/doctor.statistics/deptLists'
const rows = (query = {}) => resolveDeptStats(path, query, snapshot).data.lists
test('department options, query format, strict route allowlist', () => {
assert.deepEqual(resolveDeptStats('/adminapi/dept.dept/all', {}, snapshot).data.map(d => [d.id, d.name]), [[1, '演示一组'], [2, '演示二组'], [3, '无预约组']])
assert.equal(resolveDeptStats('/adminapi/dept.dept/edit', {}, snapshot), null)
const reply = resolveDeptStats(path, new URLSearchParams({ dept_id: '1' }), snapshot)
assert.deepEqual([reply.code, reply.show, reply.msg, reply.data.count], [1, 0, '', 1])
assert.equal(reply.data.lists[0].dept_id, 1)
})
test('today: joins via assistant, status counts reconcile, rates use total, no padded empty department', () => {
assert.deepEqual(rows(), [
{ dept_id: 1, dept_name: '演示一组', registered_count: 1, completed_count: 1, canceled_count: 0, expired_count: 1, total_count: 3, completion_rate: 33.33, time_range: '今天 (2026-03-01)', start_date: '2026-03-01', end_date: '2026-03-01' },
{ dept_id: 2, dept_name: '演示二组', registered_count: 0, completed_count: 0, canceled_count: 1, expired_count: 0, total_count: 1, completion_rate: 0, time_range: '今天 (2026-03-01)', start_date: '2026-03-01', end_date: '2026-03-01' }
])
})
test('week/month include today and 6/29 previous calendar dates across a month boundary', () => {
for (const [time_type, start, expected] of [['week', '2026-02-23', [4, 1]], ['month', '2026-01-31', [4, 3]]]) {
const result = rows({ time_type })
assert.deepEqual(result.map(r => r.total_count), expected)
assert.ok(result.every(r => r.start_date === start && r.end_date === '2026-03-01'))
}
})
test('custom dates and department narrow together; links reconcile to the matching appointments', () => {
const [row] = rows({ time_type: 'custom', start_date: '2026-02-22', end_date: '2026-03-01', dept_id: '2' })
const members = snapshot.assistants.filter(a => a.dept_id === row.dept_id).map(a => a.id)
const detail = snapshot.appointments.filter(a => members.includes(a.assistant_id) && a.date >= row.start_date && a.date <= row.end_date)
assert.equal(row.time_range, '自定义 (2026-02-22 至 2026-03-01)')
assert.equal(row.total_count, 2)
assert.equal(detail.length, row.total_count)
for (const status of ['registered', 'completed', 'canceled', 'expired']) {
assert.equal(row[status + '_count'], detail.filter(r => r.status === status).length)
}
})
test('no matching dates, no matching appointments or unknown department returns an empty list', () => {
assert.deepEqual(rows({ time_type: 'custom', start_date: '2000-01-01', end_date: '2000-12-31' }), [])
assert.deepEqual(rows({ dept_id: '3' }), [])
assert.deepEqual(rows({ dept_id: '999' }), [])
assert.deepEqual(rows({ time_type: 'custom' }), rows())
})
+68
View File
@@ -0,0 +1,68 @@
// Synthetic *accounts*, not patients. Only this local adapter knows about the demo cross-links.
const channels = ['微信小程序', '微信公众号', '手机H5', '电脑PC', '苹果APP', '安卓APP']
const aliases = ['青竹', '晴川', '听雨', '小满', '晨光', '山月', '晚舟']
const ok = data => ({ code: 1, msg: '', show: 0, data })
export function memberIdForPatient(patientId) {
if (!['number', 'string'].includes(typeof patientId) || !/^\d+$/.test(String(patientId))) return null
const id = Number(patientId)
return id > 0 && Number.isSafeInteger(70000 + id) ? 70000 + id : null
}
function positiveInt(raw, fallback, max = Number.MAX_SAFE_INTEGER) {
const n = Number(raw)
return Number.isSafeInteger(n) && n > 0 ? Math.min(n, max) : fallback
}
function dateBefore(day, offset) {
const date = new Date(day + 'T00:00:00Z')
date.setUTCDate(date.getUTCDate() - offset)
return date.toISOString().slice(0, 10)
}
function accounts({ patients, orders, appointments = [] }) {
// The order snapshot carries the fixed local demo day; never call out for identity or avatar data.
const anchor = orders[0]?.create_time.slice(0, 10) || '2026-01-31'
const orderCounts = new Map()
for (const order of orders) orderCounts.set(order.patient_id, (orderCounts.get(order.patient_id) || 0) + 1)
const appointmentCounts = new Map()
for (const appt of appointments) appointmentCounts.set(appt.patient_id, (appointmentCounts.get(appt.patient_id) || 0) + 1)
return patients.map((patient, i) => {
const ordinal = String(i + 1).padStart(2, '0')
const id = memberIdForPatient(patient.id)
return {
id, sn: 'U-DEMO-' + patient.id, nickname: aliases[i % aliases.length] + '·示例' + ordinal,
avatar: '', account: 'demo_user_' + ordinal, mobile: patient.phone,
channel: channels[i % channels.length], sex: ['未知', '女', '男'][i % 3],
create_time: dateBefore(anchor, patients.length + 10 - i) + ' 08:30:00',
login_time: dateBefore(anchor, i % 5 + 1) + ' 09:15:00',
real_name: i % 4 ? '模拟姓名' + ordinal : '', user_money: (i % 4 * 15.5).toFixed(2),
// Preview-only navigation context. Account balances are not derived from patient orders.
patient_id: patient.id, patient_name: patient.patient_name,
order_count: orderCounts.get(patient.id) || 0, appointment_count: appointmentCounts.get(patient.id) || 0
}
}).sort((a, b) => b.id - a.id)
}
export function resolvePeople(pathname, params, snapshot) {
if (!['/adminapi/user.user/lists', '/adminapi/user.user/detail'].includes(pathname)) return null
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
if (q.export != null) return null
const members = accounts(snapshot)
if (pathname === '/adminapi/user.user/detail') {
const row = members.find(u => u.id === Number(q.id))
return row ? ok(row) : { code: 0, data: null, show: 1, msg: '未找到该演示账号' }
}
const term = String(q.keyword ?? '').trim().toLowerCase()
const end = q.create_time_end?.length === 10 ? q.create_time_end + ' 23:59:59' : q.create_time_end
const rows = members.filter(u =>
(!term || [u.sn, u.account, u.nickname, u.mobile].some(s => s.toLowerCase().includes(term))) &&
(!q.channel || u.channel === channels[Number(q.channel) - 1]) &&
(!q.create_time_start || u.create_time >= q.create_time_start) &&
(!end || u.create_time <= end)
)
const size = positiveInt(q.page_size, 15, 100), page = positiveInt(q.page_no, 1)
const lists = rows.slice((page - 1) * size, page * size).map(({ id, sn, nickname, sex, avatar, account, mobile, channel, create_time }) =>
({ id, sn, nickname, sex, avatar, account, mobile, channel, create_time }))
return ok({ count: rows.length, lists, extend: {} })
}
@@ -0,0 +1,48 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { memberIdForPatient, resolvePeople } from './people.mjs'
const patients = Array.from({ length: 20 }, (_, i) => Object.freeze({
id: 501 + i, patient_name: '演示患者' + (i + 1), phone: '000****' + (1000 + i)
}))
const snapshot = Object.freeze({
patients: Object.freeze(patients),
appointments: Object.freeze([{ patient_id: 501 }, { patient_id: 501 }]),
orders: Object.freeze([{ id: 10101, patient_id: 501, create_time: '2026-12-01 08:00:00' }])
})
const read = (name, params = {}) => resolvePeople('/adminapi/user.user/' + name, params, snapshot)
test('同一批账号支持分页、编号、账号、昵称、电话、来源和注册区间筛选', () => {
const first = read('lists'), second = read('lists', new URLSearchParams('page_no=2&page_size=15'))
assert.deepEqual([first.code, first.msg, first.show, first.data.count, first.data.lists.length], [1, '', 0, 20, 15])
assert.equal(second.data.lists.length, 5)
assert.equal(new Set([...first.data.lists, ...second.data.lists].map(u => u.id)).size, 20)
const [row] = second.data.lists
for (const keyword of [row.account.toUpperCase(), row.nickname, row.mobile, row.sn]) {
assert.deepEqual(read('lists', { keyword }).data.lists, [row])
}
const filtered = read('lists', { channel: 1 }).data.lists
assert.ok(filtered.length && filtered.every(r => r.channel === '微信小程序'))
assert.deepEqual(read('lists', { create_time_start: row.create_time, create_time_end: row.create_time }).data.lists, [row])
assert.equal(read('lists', { keyword: '无此账号' }).data.count, 0)
assert.equal(read('lists', { create_time_start: '2100-01-01' }).data.count, 0)
})
test('凭账号 ID 读详情,账号、预约档案和订单的键不混用', () => {
const id = memberIdForPatient(501)
const { data: member } = read('detail', { id })
assert.notEqual(id, 501)
assert.deepEqual([member.id, member.patient_id, member.patient_name, member.order_count], [id, 501, '演示患者1', 1])
assert.equal(member.appointment_count, 2)
assert.notEqual(member.nickname, member.patient_name)
assert.deepEqual(read('lists', { keyword: member.account }).data.lists.map(r => r.id), [id])
assert.equal(read('detail', { id: memberIdForPatient(520) }).data.order_count, 0)
assert.match(member.mobile, /^000\*{4}\d{4}$/)
for (const value of [0, '', null, true, '1.5', 'x']) assert.equal(memberIdForPatient(value), null)
assert.equal(read('detail', { id: 501 }).code, 0)
})
test('用户端点仅限读,不承接写操作、导出或未知路径', () => {
for (const path of ['edit', 'adjustMoney', 'export', 'arbitrary']) assert.equal(read(path), null)
for (const mode of ['1', '2']) assert.equal(read('lists', { export: mode }), null)
})
+65
View File
@@ -0,0 +1,65 @@
// The seed is a local calendar date (not a UTC timestamp). Overlapping weeks keep
// identical IDs and shifts even when the shared preview snapshot rolls forward.
const names = ['林衡', '沈知禾', '许亦安', '顾清和', '赵元宁', '叶嘉言']
const dayTimes = [
['08:30', '11:30', 'day'], ['14:00', '17:00', 'day'], ['18:00', '21:00', 'night']
]
const isoDate = d => d.toISOString().slice(0, 10)
const ok = data => ({ code: 1, data, show: 0, msg: '' })
const list = (lists, count = lists.length) => ok({ lists, count, extend: {} })
export function makeRosterSnapshot(departments, now) {
if (!departments.length) return { doctors: [], slots: [] }
const doctors = names.map((name, i) => ({
id: 201 + i, name: name + '(演示)', dept_id: departments[i % departments.length].dept_id
}))
const monday = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()))
monday.setUTCDate(monday.getUTCDate() - (monday.getUTCDay() + 6) % 7)
const slots = []
// Five weeks before and two weeks after this Monday also cover the recent-30-day views.
for (let offset = -35; offset < 21; offset++) {
const d = new Date(monday)
d.setUTCDate(d.getUTCDate() + offset)
const date = isoDate(d), ordinal = Math.floor(d.getTime() / 86400000)
doctors.forEach((doctor, i) => {
const phase = (ordinal + i * 2) % 9
if (phase === 1 || phase === 6) return // No segment ≠ cancelled/closed shift.
const status = phase === 4 ? 2 : phase === 5 ? 4 : phase === 7 && i % 2 ? 3 : 1
const shifts = status === 1 && phase === 0 ? [0, 1] : [phase === 2 ? 2 : phase % 2]
for (const j of shifts) {
const [start_time, end_time, shift_type] = dayTimes[j]
const quota = status === 1 ? (phase % 3 === 0 ? 0 : 8 + i % 5) : 0
slots.push({
id: Number(date.replaceAll('-', '')) * 100 + i * 10 + j, doctor_id: doctor.id,
date, period: 'segment', start_time, end_time, shift_type, slot_minutes: 15,
status, quota, max_patients: 0, booked_count: 0, remark: ''
})
}
})
}
slots.sort((a, b) => a.date.localeCompare(b.date) || a.start_time.localeCompare(b.start_time) || a.id - b.id)
return { doctors, slots }
}
export function resolveRoster(pathname, params, snapshot) {
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
if (q.export != null) return null
if (pathname === '/adminapi/auth.admin/lists') {
// Never turn the general account-management API into an unscoped preview endpoint.
if (String(q.role_id) !== '1' || String(q.exclude_disabled) !== '1') return null
const rows = snapshot.doctors.filter(d => !q.name || d.name.includes(String(q.name).trim()))
const positive = (n, fallback) => Number.isSafeInteger(+n) && +n > 0 ? +n : fallback
const page = positive(q.page_no, 1), size = Math.min(1000, positive(q.page_size, 15))
return list(rows.slice((page - 1) * size, page * size).map(d => ({
...d, dept_id: [d.dept_id], dept_name: snapshot.departments.find(dep => dep.dept_id === d.dept_id)?.dept_name || ''
})), rows.length)
}
if (pathname !== '/adminapi/doctor.roster/lists') return null
const matches = snapshot.slots.filter(s =>
(!q.start_date || s.date >= q.start_date) && (!q.end_date || s.date <= q.end_date) &&
(!q.doctor_id || s.doctor_id === Number(q.doctor_id)) &&
(!q.status || s.status === Number(q.status)) && (!q.period || s.period === q.period)
)
// Production RosterLists returns all matching segments for the displayed week, without pagination.
return list(matches)
}
@@ -0,0 +1,59 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { makeRosterSnapshot, resolveRoster } from './roster.mjs'
// Deliberately not contiguous: no logic may use a department ID as an array index.
const departments = [{ dept_id: 17, dept_name: '预览一组' }, { dept_id: 39, dept_name: '预览二组' }]
const seed = new Date(2027, 0, 1, 9, 17)
const snapshot = { ...makeRosterSnapshot(departments, seed), departments }
const doctorPath = '/adminapi/auth.admin/lists', rosterPath = '/adminapi/doctor.roster/lists'
const doctorQuery = { role_id: '1', exclude_disabled: '1' }
const read = (path, q) => {
const response = resolveRoster(path, q, snapshot)
assert.deepEqual([response.code, response.show, response.msg], [1, 0, ''])
return response.data
}
test('相邻周跨年、同日期排班不漂移、每段有合法医生部门关系', () => {
const { slots, doctors } = snapshot
assert.ok(slots.length > 0)
assert.equal(new Set(slots.map(s => s.id)).size, slots.length)
assert.ok(doctors.every(d => departments.some(dep => dep.dept_id === d.dept_id)))
assert.ok(slots.every(s => doctors.some(d => d.id === s.doctor_id) && s.start_time < s.end_time))
assert.deepEqual(new Set(slots.map(s => s.status)), new Set([1, 2, 3, 4]))
for (const [start, end] of [['2026-12-21','2026-12-27'],['2026-12-28','2027-01-03'],['2027-01-04','2027-01-10']]) {
const week = read(rosterPath, { start_date: start, end_date: end })
assert.equal(week.count, week.lists.length)
assert.equal(new Set(week.lists.map(s => s.date)).size, 7)
assert.ok(week.lists.every(s => s.date >= start && s.date <= end))
}
const next = makeRosterSnapshot(departments, new Date(2027, 0, 4))
const interval = s => s.date >= '2026-12-28' && s.date <= '2027-01-10'
assert.deepEqual(slots.filter(interval), next.slots.filter(interval))
assert.deepEqual(makeRosterSnapshot([], seed), { doctors: [], slots: [] })
})
test('医生列表限制角色、部门和分页;排班按日期、医生与状态合并过滤', () => {
const all = read(doctorPath, new URLSearchParams(doctorQuery))
assert.equal(all.count, snapshot.doctors.length)
const d = all.lists[0]
assert.deepEqual(d.dept_id, [17])
assert.equal(d.dept_name, departments[0].dept_name)
assert.deepEqual(read(doctorPath, { ...doctorQuery, name: d.name }).lists, [d])
assert.deepEqual(read(doctorPath, { ...doctorQuery, page_no: 2, page_size: 1 }).lists, [all.lists[1]])
const slot = snapshot.slots.find(s => s.doctor_id === d.id && s.status === 1)
const matches = read(rosterPath, { start_date: slot.date, end_date: slot.date, doctor_id: String(d.id), status: '1', period: 'segment' })
assert.ok(matches.lists.some(s => s.id === slot.id))
assert.ok(matches.lists.every(s => s.doctor_id === d.id && s.status === 1 && s.date === slot.date))
assert.equal(read(rosterPath, { doctor_id: -1 }).count, 0)
})
test('通用账号、导出、写入和未开放路由均不模拟', () => {
for (const q of [{}, { role_id: 1 }, { ...doctorQuery, role_id: 2 }, { ...doctorQuery, export: 1 }]) {
assert.equal(resolveRoster(doctorPath, q, snapshot), null)
}
for (const action of ['save', 'delete', 'batchSave', 'copy', 'detail']) {
assert.equal(resolveRoster('/adminapi/doctor.roster/' + action, {}, snapshot), null)
}
assert.equal(resolveRoster(rosterPath, { export: 2 }, snapshot), null)
})
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect x="1" y="1" width="38" height="38" rx="11" fill="#5D87FF"/><path d="M10 26c0-11 6-17 20-17 0 13-6 20-17 19m0-2 13-13m-8 8v-5m2 3h5" fill="none" stroke="#FFFFFF" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.9"/></svg>

After

Width:  |  Height:  |  Size: 301 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect x="1" y="1" width="38" height="38" rx="11" fill="#13765e"/><path d="M10 26c0-11 6-17 20-17 0 13-6 20-17 19m0-2 13-13m-8 8v-5m2 3h5" fill="none" stroke="#f5fffa" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.9"/></svg>

After

Width:  |  Height:  |  Size: 301 B

+65
View File
@@ -0,0 +1,65 @@
// Import preview pages explicitly: no production authentication or external call SDK initialization.
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/default/index.vue'
const meta = (title: string, icon: string, other: Record<string, unknown> = {}) => ({
title,
icon,
keepAlive: true,
localPreview: true,
...other
})
export const pages = [
{
path: '/workbench',
name: 'preview-workbench',
component: () => import('@/views/workbench/index.vue'),
meta: meta('数据工作台', 'el-icon-DataAnalysis')
},
{
path: '/members',
name: 'preview-members',
component: () => import('@/views/consumer/lists/index.vue'),
meta: meta('用户列表', 'el-icon-User')
},
{
path: '/members/detail',
name: 'preview-member-detail',
component: () => import('@/views/consumer/lists/detail.vue'),
meta: meta('用户详情', '', { hidden: true, activeMenu: '/members' })
},
{
path: '/appointments',
name: 'preview-appointments',
component: () => import('./AppointmentLedger.vue'),
meta: meta('预约明细', 'el-icon-Calendar')
},
{
path: '/roster',
name: 'preview-roster',
component: () => import('@/views/doctor/roster.vue'),
meta: meta('医生排班', 'el-icon-Clock')
},
{
path: '/order',
name: 'preview-order',
component: () => import('@/views/order/index.vue'),
meta: meta('订单列表', 'el-icon-Tickets')
},
{
path: '/dept-stats',
name: 'preview-dept-stats',
component: () => import('@/views/doctor/dept-tongji.vue'),
meta: meta('部门预约统计', 'el-icon-PieChart')
}
]
const router = createRouter({
history: createWebHistory('/admin/'),
routes: [
{ path: '/', component: Layout, redirect: '/workbench', children: pages },
{ path: '/:other(.*)*', redirect: '/workbench' }
]
})
export const getRoutePath = (perm: string) => (perm === 'user.user/detail' ? '/members/detail' : '')
export const filterAsyncRoutes = () => []
export const resetRouter = () => undefined
export default router
+84
View File
@@ -0,0 +1,84 @@
// A loopback static/fixture server. No proxy, database driver, transport client or environment credentials.
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const dist = fileURLToPath(new URL('../node_modules/.zyt-ui-preview/dist/', import.meta.url))
const host = '127.0.0.1'
const demoPort = 5180, entryPort = 5178
const demoOrigin = `http://${host}:${demoPort}`, entryAuthority = `${host}:${entryPort}`
const entryDestination = 'http://127.0.0.1:5179/admin/#'
// This listener serves no bytes from disk and has no transport to 5179.
// An explicit empty fragment prevents browsers carrying an old fragment into 5179.
export function serveOldEntry(req, res) {
res.setHeader('Cache-Control', 'no-store')
res.setHeader('Referrer-Policy', 'no-referrer')
res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'; base-uri 'none'")
const end = (status, headers) => { res.writeHead(status, headers); res.end() }
const h = req.headers
if (h.host !== entryAuthority || (h.origin && h.origin !== 'http://' + entryAuthority) || h['sec-fetch-site'] === 'cross-site') return end(403)
if (req.method !== 'GET') return end(405, {Allow:'GET'})
if ((h['sec-fetch-mode'] && h['sec-fetch-mode'] !== 'navigate') ||
(h['sec-fetch-dest'] && h['sec-fetch-dest'] !== 'document') ||
(h.accept && !/(?:^|,)\s*(?:text\/html|\*\/\*)(?:[;,]|$)/i.test(h.accept)) ||
h.authorization || h.token) return end(403)
const pathname = req.url?.split('?', 1)[0]
if (pathname !== '/' && !/^\/admin(?:\/[a-zA-Z0-9_-]+)*\/?$/.test(pathname)) return end(404)
if (/(?:^|\/)(?:assets|static|adminapi|api|api-proxy|proxy)(?:\/|$)/i.test(pathname)) return end(404)
return end(302, {Location:entryDestination})
}
// The fixture module is deliberately loaded only on explicit demo startup.
async function createDemoHandler() {
const { resolveFixture } = await import('./fixtures.mjs')
await readFile(path.join(dist,'local-preview/index.html'))
return async (req, res) => serveDemo(resolveFixture, req, res)
}
const csp = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'none'; frame-src 'none'; worker-src 'none'; form-action 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
const types = {'.js':'application/javascript','.css':'text/css','.svg':'image/svg+xml','.woff2':'font/woff2','.woff':'font/woff','.png':'image/png','.jpg':'image/jpeg','.webp':'image/webp','.gif':'image/gif','.ttf':'font/ttf'}
const routes = new Set(['/','/admin','/admin/','/admin/workbench','/admin/order','/admin/members','/admin/members/detail','/admin/appointments','/admin/roster','/admin/dept-stats'])
async function serveDemo(resolveFixture,req,res) {
res.setHeader('Content-Security-Policy',csp); res.setHeader('Cache-Control','no-store'); res.setHeader('X-Content-Type-Options','nosniff'); res.setHeader('Referrer-Policy','no-referrer')
const send=(status,type,body)=>{ res.writeHead(status,{'Content-Type':type}); res.end(req.method==='HEAD' ? undefined : body) }
const json=(status,obj)=>send(status,'application/json; charset=utf-8',JSON.stringify(obj))
const deny=(status)=>json(status,{code:0,show:1,msg:'本地只读预览:此操作未开放',data:null})
if(req.headers.host !== `${host}:${demoPort}` || (req.headers.origin && req.headers.origin !== demoOrigin) || req.headers['sec-fetch-site']==='cross-site') return deny(403)
if(!req.url?.startsWith('/') || req.url.startsWith('//')) return deny(400)
const {pathname,searchParams}=new URL(req.url,demoOrigin)
if(pathname.startsWith('/adminapi/')) {
let params=Object.fromEntries(searchParams)
if(pathname==='/adminapi/order.order/detail') {
if(req.method!=='POST') return deny(405)
if(!req.headers['content-type']?.startsWith('application/json')) return deny(415)
let raw=''; for await(const chunk of req){ raw+=chunk; if(raw.length>4096) return deny(413) }
try { params=JSON.parse(raw); if(!params || typeof params!=='object' || Array.isArray(params)) return deny(400) } catch { return deny(400) }
} else if(req.method!=='GET') return deny(405)
const result=resolveFixture(pathname,params); return result ? json(200,result) : deny(403)
}
if(!['GET','HEAD'].includes(req.method)) return deny(405)
if(routes.has(pathname)) return send(200,'text/html; charset=utf-8',await readFile(path.join(dist,'local-preview/index.html')))
const asset=pathname.match(/^\/admin\/assets\/([a-zA-Z0-9_.-]+)$/)
if(asset && types[path.extname(asset[1])]) {
try { return send(200,types[path.extname(asset[1])],await readFile(path.join(dist,'assets',asset[1]))) } catch { return deny(404) }
}
return deny(404)
}
function selectPort(args) {
if (args.length === 0 || (args.length === 1 && args[0] === String(entryPort))) return entryPort
if (args.length === 1 && args[0] === String(demoPort)) return demoPort
throw new Error('端口仅支持 5178(旧入口跳转)或 5180(合成数据演示)')
}
export async function createLocalListener(args) {
const port = selectPort(args)
const handler = port === demoPort ? await createDemoHandler() : serveOldEntry
return {port, handler}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const {port, handler} = await createLocalListener(process.argv.slice(2))
const label = port === demoPort ? `合成数据演示:${demoOrigin}/admin/workbench` : `旧入口仅跳转到正式数据查询:${entryDestination}`
http.createServer(async (req, res) => {
try { await handler(req, res) }
catch { if (!res.headersSent) res.writeHead(500); res.end() }
}).listen(port, host, () => console.log(label))
}
+75
View File
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict'
import { copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
const host = '127.0.0.1:5178'
const destination = 'http://127.0.0.1:5179/admin/#'
async function request(handler, url, headers = {}, method = 'GET') {
const res = {
headers: {},
setHeader(name, value) { this.headers[name] = value },
writeHead(status, headers) { this.status = status; Object.assign(this.headers, headers) },
end(body) { this.body = body }
}
await handler({method, url, headers: {host, ...headers}}, res)
return res
}
test('无构建和模拟数据时默认/显式 5178 仍可导航;5180 才依赖演示文件', async (t) => {
const root = await mkdtemp(path.join(tmpdir(), 'zyt-preview-entry-'))
t.after(() => rm(root, {recursive: true, force: true}))
const dir = path.join(root, 'local-preview')
await mkdir(dir)
const file = path.join(dir, 'server.mjs')
await copyFile(new URL('./server.mjs', import.meta.url), file)
const {createLocalListener} = await import(pathToFileURL(file).href)
for (const args of [[], ['5178']]) {
const {port, handler} = await createLocalListener(args)
assert.equal(port, 5178)
for (const url of ['/', '/admin', '/admin/', '/admin/workbench', '/admin/login?redirect=//dummy.invalid', '/admin/members/detail?id=123&token=dummy']) {
const res = await request(handler, url, {'sec-fetch-mode':'navigate', 'sec-fetch-dest':'document', accept:'text/html,application/xhtml+xml'})
assert.equal(res.status, 302, url)
assert.equal(res.headers.Location, destination, url)
assert.equal(res.headers['Cache-Control'], 'no-store')
assert.equal(res.headers['Referrer-Policy'], 'no-referrer')
assert.equal(res.body, undefined)
}
}
await assert.rejects(createLocalListener(['5180']), {code:'ERR_MODULE_NOT_FOUND'})
for (const args of [['5179'], ['0'], [''], ['5178','5180']]) {
await assert.rejects(createLocalListener(args), /端口仅支持/)
}
// A miniature, local-only demo build verifies that the explicit mode still serves a page and a fixture.
const dist = path.join(root, 'node_modules/.zyt-ui-preview/dist/local-preview')
await mkdir(dist, {recursive:true})
await writeFile(path.join(dist, 'index.html'), '<h1>offline demo</h1>')
await writeFile(path.join(dir, 'fixtures.mjs'), 'export const resolveFixture = () => ({data:"demo"})')
const {port, handler} = await createLocalListener(['5180'])
const headers = {host:'127.0.0.1:5180'}
assert.equal(port, 5180)
assert.equal(String((await request(handler, '/admin/workbench', headers)).body), '<h1>offline demo</h1>')
assert.deepEqual(JSON.parse((await request(handler, '/adminapi/order.order/lists', headers)).body), {data:'demo'})
})
test('5178 拒绝接口、资源、非导航请求和账号提交,不返回 Location 或数据', async () => {
const {createLocalListener} = await import('./server.mjs')
const {handler} = await createLocalListener([])
const cases = [
...['/adminapi/order.order/lists', '/api-proxy/adminapi/order.order/lists', '/admin/assets/js',
'/admin/assets/style.css', '/admin/static/logo', '/admin/api/list', '/admin/favicon.ico', '/.env',
'//dummy.invalid/admin', '/admin/../admin', '/admin/%2f%2fdummy.invalid'].map(url => [url, {}, 'GET', 404]),
...['POST','PUT','DELETE','OPTIONS','HEAD'].map(method => ['/admin/login', {}, method, 405]),
...[{host:'dummy.invalid'}, {origin:'https://dummy.invalid'}, {'sec-fetch-site':'cross-site'},
{'sec-fetch-mode':'cors'}, {'sec-fetch-dest':'script'}, {accept:'application/json'},
{authorization:'test'}, {token:'test'}].map(headers => ['/admin/', headers, 'GET', 403])
]
for (const [url, headers, method, status] of cases) {
const res = await request(handler, url, headers, method)
assert.equal(res.status, status, method + ' ' + url)
assert.equal(res.headers.Location, undefined)
assert.equal(res.body, undefined)
}
})
+22
View File
@@ -0,0 +1,22 @@
// Run the real Pinia settings module against an isolated in-memory document/cache.
const fs = require('node:fs'), path = require('node:path'), assert = require('node:assert/strict')
const ts = require('typescript'), { createPinia, setActivePinia } = require('pinia')
const root = path.resolve(process.argv[2] || path.join(__dirname,'..')), cache = new Map()
const load = (file, imports = {}) => {
const module = {exports:{}}
const js = ts.transpileModule(fs.readFileSync(path.join(root,file),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText
new Function('require','exports','module',js)(id => Object.hasOwn(imports,id) ? imports[id] : require(id), module.exports, module)
return module.exports
}
const config = load('src/config/setting.ts')
function enter(preview) {
global.document = {documentElement:{dataset:preview?{adminUi:'v2'}:{}}}
setActivePinia(createPinia())
return load('src/stores/modules/setting.ts',{'@/config/setting':config,'@/enums/cacheEnums':{SETTING_KEY:'setting'},'@/utils/cache':{get:k=>cache.get(k),set:(k,v)=>cache.set(k,v),remove:k=>cache.delete(k)},'@/utils/theme':{setTheme(){}}}).default()
}
let store=enter(false)
if(typeof store.toggleAdminUi!=='function') { assert.equal(store.adminUi,undefined); console.log('classic-only'); }
else {
assert.equal(store.adminUi,'legacy'); store.toggleAdminUi(); assert.equal(document.documentElement.dataset.adminUi,'v2'); assert.equal(enter(false).adminUi,'v2')
store=enter(true); assert.equal(store.adminUi,'v2'); store.toggleAdminUi(); assert.equal(document.documentElement.dataset.adminUi,'legacy'); assert.equal(enter(false).adminUi,'v2'); console.log('classic/new switch; preview preference isolated')
}
@@ -0,0 +1,66 @@
"""Compare rendered elements, not just declared CSS tokens, to Art Design Pro f3aaf58."""
import argparse
import json
import re
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
parser = argparse.ArgumentParser()
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--record-only', action='store_true', help='record the pre-correction build without asserting parity')
a = parser.parse_args()
a.out.mkdir(exist_ok=True, parents=True)
origin = 'http://127.0.0.1:5180/'
read_colors = """() => {
const style = (sel) => getComputedStyle(document.querySelector(sel));
const sample = (sel, key) => {
const value = style(sel)[key];
// Canvas normalises srgb color-mix / rgb / hex to the actual 8-bit pixel color.
const ctx=document.createElement('canvas').getContext('2d');ctx.fillStyle=value;ctx.fillRect(0,0,1,1);
return '#' + [...ctx.getImageData(0,0,1,1).data].slice(0,3).map(x=>x.toString(16).padStart(2,'0')).join('').toUpperCase();
};
const bg=sel=>sample(sel,'backgroundColor');
return {primaryButton:bg('.wb-refresh-btn'), page:bg('.main-wrap'),sidebar:bg('.side'),
sidebarWidth:Math.round(document.querySelector('.app-aside').getBoundingClientRect().width),
activeItem:bg('.menu .el-menu-item.is-active'),activeText:sample('.menu .el-menu-item.is-active span','color'),
card:bg('.wb-section'),cardRadius:style('.wb-section').borderTopLeftRadius,cardBorder:style('.wb-section').borderTopColor,
cardShadow:style('.wb-section').boxShadow, buttonHeight:style('.wb-refresh-btn').height,
menuItemHeight:style('.menu .el-menu-item.is-active').height,
selectedColorToken:getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary-light-9').trim()};
}"""
modes = {}; external=[]; palette=[]
with sync_playwright() as pw:
browser=pw.chromium.launch(headless=True, args=['--disable-background-networking','--no-proxy-server','--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'])
ctx=browser.new_context(viewport={'width':1440,'height':960},color_scheme='light',service_workers='block')
def local(route):
if route.request.url.startswith(origin): return route.continue_()
external.append(route.request.url); return route.abort()
ctx.route('**/*',local); page=ctx.new_page(); page.goto(origin+'admin/workbench',wait_until='networkidle'); expect(page.locator('.wb-refresh-btn')).to_be_visible()
for mode in ['light','dark','classic']:
if mode=='dark': page.emulate_media(color_scheme='dark'); expect(page.locator('html')).to_have_class(re.compile('dark'))
if mode=='classic':
page.emulate_media(color_scheme='light'); page.locator('[data-admin-ui-toggle]').click(); expect(page.locator('html')).to_have_attribute('data-admin-ui','legacy')
page.mouse.move(1430,950); page.wait_for_timeout(350)
modes[mode]=page.evaluate(read_colors); page.screenshot(path=str(a.out/(mode+'.png')))
if not a.record_only:
page.locator('[data-admin-ui-toggle]').click(); page.locator('.navbar .setting').click()
drawer=page.locator('.setting-drawer .el-drawer:visible, .el-drawer:visible').last
expect(drawer.get_by_role('button',name='设计菜单')).to_have_attribute('aria-pressed','true')
expect(drawer.get_by_role('spinbutton').first).to_have_value('230')
drawer.locator('.el-color-picker').click()
swatches=page.locator('.el-color-predefine__color-selector:visible'); expect(swatches).to_have_count(7)
palette=swatches.evaluate_all("els => els.map(e => {const c=getComputedStyle(e.querySelector('div')).backgroundColor.match(/\\d+/g);return '#'+c.slice(0,3).map(v=>(+v).toString(16).padStart(2,'0')).join('').toUpperCase()})")
assert palette == ['#5D87FF','#B48DF3','#1D84FF','#60C041','#38C0FC','#F9901F','#FF80C8'],palette
swatches.nth(1).click(); page.locator('.el-color-picker__panel:visible, .el-color-picker-panel:visible').last.get_by_role('button',name=re.compile('确定|确认')).click()
expect(page.locator('.wb-refresh-btn')).to_have_css('background-color','rgb(180, 141, 243)')
drawer.get_by_role('button',name='重置主题').click(); expect(page.locator('.wb-refresh-btn')).to_have_css('background-color','rgb(93, 135, 255)')
browser.close()
report={'upstream':'f3aaf58eec1a0e988f162352c33862327a484f95','actual':modes,'settings_palette':palette,'external_requests':external}
(a.out/'computed.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n'); print(json.dumps(report,ensure_ascii=False)); assert not external
if not a.record_only:
expected={'light':{'primaryButton':'#5D87FF','page':'#FAFBFC','sidebar':'#FFFFFF','activeItem':'#EEF3FF','activeText':'#5D87FF','card':'#FFFFFF','menuItemHeight':'42px','buttonHeight':'36px','cardRadius':'16px','cardBorder':'rgba(0, 0, 0, 0.08)','cardShadow':'none'}, 'dark':{'primaryButton':'#5D87FF','page':'#070707','sidebar':'#161618','activeItem':'#27282D','activeText':'#5D87FF','card':'#161618'}, 'classic':{'primaryButton':'#4A5DFF','sidebar':'#1D2124'}}
for mode,checks in expected.items():
for k,v in checks.items(): assert modes[mode][k]==v,(mode,k,v,modes[mode][k])
assert modes['light']['sidebarWidth'] in (230,231),modes['light']['sidebarWidth'] # pane + optional one-pixel boundary
print('PASS: Art theme parameters match rendered controls; classic appearance preserved.')
+22
View File
@@ -0,0 +1,22 @@
// Check the running local preview only; do not follow redirects, and do not use credentials.
import assert from 'node:assert/strict'
const origin='http://127.0.0.1:5180'
async function check(method,p,status,opts={}) {
const r=await fetch(origin+p,{...opts,method,redirect:'error'}); assert.equal(r.status,status,`${method} ${p}`); console.log(`${method} ${p} -> ${r.status}`); return r
}
const page=await check('GET','/admin/workbench',200); assert.match(page.headers.get('content-security-policy'),/connect-src 'self';/)
const rows=await (await check('GET','/adminapi/order.order/lists',200)).json(); assert.ok(rows.data.lists[0].order_no.startsWith('DEMO-'))
await check('POST','/adminapi/order.order/detail',200,{headers:{'content-type':'application/json'},body:JSON.stringify({id:rows.data.lists[0].id})})
await check('POST','/adminapi/order.order/pay',405)
await check('GET','/adminapi/order.order/syncWechatWorkBills',403)
await check('GET','/adminapi/order.order/export?export=2',403)
await check('GET','/api-proxy/adminapi/order.order/lists',404)
await check('GET','/adminapi/order.order/lists',403,{headers:{origin:'http://different-origin.invalid'}})
await check('GET','/.env',404)
// The extra pages are direct-linkable; new modules never widen the write boundary.
for (const path of ['/admin/members','/admin/members/detail?id=70501','/admin/roster','/admin/appointments','/admin/dept-stats']) await check('GET',path,200)
await check('GET','/adminapi/local.preview/appointments?page_size=1',200)
await check('POST','/adminapi/doctor.roster/save',405)
await check('POST','/adminapi/user.user/adjustMoney',405)
await check('GET','/adminapi/doctor.roster/delete',403)
await check('GET','/adminapi/auth.admin/lists',403)
+31
View File
@@ -0,0 +1,31 @@
// Deferred same-origin script: no remote dependency, inline handler or application API.
;(function () {
var boot = document.getElementById('admin-boot')
if (!boot) return
try {
// Only appearance keys are read. Vue/Pinia remains the owner after mount.
function readPreference(name) {
var record = JSON.parse(localStorage.getItem('like_admin_' + name) || 'null')
return record && (!record.expire || record.expire >= Date.now() / 1000) ? record.value : null
}
var appearance = readPreference('admin_ui') || document.documentElement.dataset.defaultAdminUi
var profile = appearance === 'v2' && readPreference('admin_ui_v2_setting')
var mode = appearance === 'v2' ? (profile && profile.colorMode) : localStorage.getItem('vueuse-color-scheme')
if (mode === 'dark' || mode === 'light') boot.dataset.mode = mode
} catch (_) { /* Browser privacy settings: CSS follows the system. */ }
// A slow network is not a failure. Keep waiting unless the user chooses to reload.
var slow = setTimeout(function () {
if (boot.dataset.state === 'loading') boot.dataset.state = 'slow'
}, 12000)
function entryFailed(event) {
// Optional SDK/style/image errors must never turn a healthy app into a failure.
var script = event.target
if (script && script.tagName === 'SCRIPT' && script.type === 'module') boot.dataset.state = 'error'
}
window.addEventListener('error', entryFailed, true)
window.addEventListener('admin:mounted', function () {
clearTimeout(slow)
window.removeEventListener('error', entryFailed, true)
}, { once: true })
})()
+50
View File
@@ -0,0 +1,50 @@
/* Native entry, including the interval before Vue's first chunk is evaluated. */
#admin-boot {
--boot-bg: #fafbfc;
--boot-ink: #323251;
--boot-muted: #596681;
--boot-accent: #5d87ff;
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: var(--boot-bg);
color: var(--boot-ink);
text-align: center;
font: 14px/1.6 system-ui, "PingFang SC", "Microsoft YaHei", sans-serif;
pointer-events: none;
}
#admin-boot[data-mode="dark"] {
--boot-bg: #121318; --boot-ink: #e8ecf3; --boot-muted: #a8b2c7; --boot-accent: #829eff;
}
@media (prefers-color-scheme: dark) {
#admin-boot:not([data-mode="light"]) {
--boot-bg: #121318; --boot-ink: #e8ecf3; --boot-muted: #a8b2c7; --boot-accent: #829eff;
}
}
#admin-boot .boot-mark { display: block; margin: 0 auto 18px; color: var(--boot-accent); animation: boot-turn 1.6s linear infinite; }
#admin-boot strong { font-size: 18px; font-weight: 600; letter-spacing: .04em; }
#admin-boot p { margin: 5px 12px 0; color: var(--boot-muted); }
#admin-boot [data-message], #admin-boot-retry { display: none; }
#admin-boot[data-state="loading"] [data-message="loading"],
#admin-boot[data-state="slow"] [data-message="slow"],
#admin-boot[data-state="error"] [data-message="error"] { display: inline; }
#admin-boot[data-state="error"] .boot-mark { animation: none; }
#admin-boot:not([data-state="loading"]) #admin-boot-retry {
display: inline-block; margin-top: 10px; padding: 4px 12px; color: inherit;
text-decoration: underline; text-underline-offset: 3px; pointer-events: auto;
}
@keyframes boot-turn { to { transform: rotate(1turn); } }
/* Indeterminate like the Art header. No fake percentage, overlay or scroll lock. */
#admin-route-progress {
position: fixed; top: 0; left: 0; width: 100%; height: 3px; z-index: 2400;
background: var(--el-color-primary, #5d87ff);
pointer-events: none; transform-origin: left; transform: scaleX(.22);
animation: admin-route-advance 8s cubic-bezier(.12,.76,.22,1) forwards;
}
@keyframes admin-route-advance { to { transform: scaleX(.92); } }
@media (prefers-reduced-motion: reduce) {
#admin-boot .boot-mark, #admin-route-progress { animation: none; }
#admin-route-progress { transform: scaleX(.4); }
}
+15 -23
View File
@@ -1,18 +1,21 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue' import { computed } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { useDark, useThrottleFn, useWindowSize } from '@vueuse/core' import { useWindowSize } from '@vueuse/core'
import zhCn from 'element-plus/es/locale/lang/zh-cn' import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ScreenEnum } from './enums/appEnums' import { ScreenEnum } from './enums/appEnums'
import useAppStore from './stores/modules/app' import useAppStore from './stores/modules/app'
import useSettingStore from './stores/modules/setting' import useSettingStore, { useAdminDark } from './stores/modules/setting'
import useUserStore from './stores/modules/user' import useUserStore from './stores/modules/user'
import ChatNotifyToast from './components/chat-notify-toast/index.vue' import ChatNotifyToast from './components/chat-notify-toast/index.vue'
import RevisitDueToast from './components/revisit-due-toast/index.vue' import RevisitDueToast from './components/revisit-due-toast/index.vue'
import RouteLoadNotice from './components/route-load-notice/index.vue'
const appStore = useAppStore() const appStore = useAppStore()
const settingStore = useSettingStore() const settings = useSettingStore()
// Resolve the saved appearance, system mode and palette before routes render.
useAdminDark()
const userStore = useUserStore() const userStore = useUserStore()
const route = useRoute() const route = useRoute()
@@ -27,28 +30,16 @@ const elConfig = {
zIndex: 2000, zIndex: 2000,
locale: zhCn locale: zhCn
} }
const isDark = useDark()
onMounted(async () => {
console.log('主题颜色',isDark.value)
//设置主题色
settingStore.setTheme(isDark.value)
})
const { width } = useWindowSize() const { width } = useWindowSize()
watch( watch(
width, [width, () => settings.adminUi],
useThrottleFn((value) => { ([value, ui], [previous, previousUi]) => {
if (value > ScreenEnum.SM) { // Don't reset transient v2 navigation within the same desktop breakpoint.
appStore.setMobile(false) if (ui === 'v2' && ui === previousUi && previous !== undefined &&
appStore.toggleCollapsed(false) value > ScreenEnum.SM && previous > ScreenEnum.SM &&
} else { (value < ScreenEnum.MD) === (previous < ScreenEnum.MD)) return
appStore.setMobile(true) appStore.syncSidebarViewport(value, ui)
appStore.toggleCollapsed(true) },
}
if (value < ScreenEnum.MD) {
appStore.toggleCollapsed(true)
}
}),
{ {
immediate: true immediate: true
} }
@@ -58,6 +49,7 @@ watch(
<template> <template>
<el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex"> <el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
<router-view /> <router-view />
<route-load-notice />
<ChatNotifyToast v-if="showChatNotifyToast" /> <ChatNotifyToast v-if="showChatNotifyToast" />
<!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 --> <!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 -->
<RevisitDueToast v-if="showChatNotifyToast" /> <RevisitDueToast v-if="showChatNotifyToast" />
+18
View File
@@ -0,0 +1,18 @@
<template>
<el-alert class="admin-page-hint" :type="settings.adminUi === 'v2' ? 'info' : 'warning'" :title="title" :closable="false" show-icon />
</template>
<script setup lang="ts">
import useSettingStore from '@/stores/modules/setting'
// Static page descriptions only. Errors, account state and financial warnings use el-alert directly.
defineProps<{ title: string }>()
const settings = useSettingStore()
</script>
<style scoped>
:root[data-admin-ui='v2'] .admin-page-hint {
--el-alert-bg-color: var(--zyt-surface-subtle);
color: var(--zyt-text);
}
</style>
@@ -14,6 +14,7 @@
<el-date-picker <el-date-picker
v-model="dateRangeModel" v-model="dateRangeModel"
type="daterange" type="daterange"
popper-class="list-time-filter-calendar"
value-format="YYYY-MM-DD" value-format="YYYY-MM-DD"
range-separator="至" range-separator="至"
start-placeholder="开始日期" start-placeholder="开始日期"
@@ -38,6 +39,7 @@
v-if="timeType === 'custom'" v-if="timeType === 'custom'"
v-model="dateRangeModel" v-model="dateRangeModel"
type="daterange" type="daterange"
popper-class="list-time-filter-calendar"
value-format="YYYY-MM-DD" value-format="YYYY-MM-DD"
range-separator="至" range-separator="至"
start-placeholder="开始日期" start-placeholder="开始日期"
@@ -94,3 +96,26 @@ const emit = defineEmits<{
margin-bottom: 0; margin-bottom: 0;
} }
</style> </style>
<!-- The picker is teleported outside its form. Limit this override to the shared
list filter, the new admin profile and narrow screens; keep both months reachable. -->
<style lang="scss">
@media (max-width: 640px) {
:root[data-admin-ui='v2'] .list-time-filter-calendar .el-date-range-picker {
width: min(360px, calc(100vw - 24px));
.el-picker-panel__body-wrapper {
max-height: min(62vh, 480px);
overflow-y: auto;
overscroll-behavior: contain;
}
.el-picker-panel__body { min-width: 0; }
.el-date-range-picker__content {
display: block;
width: 100%;
padding: 8px 12px;
&.is-left { border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
}
}
}
</style>
+39 -4
View File
@@ -1,12 +1,12 @@
<template> <template>
<div class="pagination"> <div class="pagination zyt-pagination" :class="{ 'zyt-pagination--standard': effectiveLayout === standardLayout }">
<el-pagination <el-pagination
v-bind="props" v-bind="props"
:pager-count="5" :pager-count="5"
v-model:currentPage="pager.page" v-model:currentPage="pager.page"
v-model:pageSize="pager.size" v-model:pageSize="pager.size"
:page-sizes="pageSizes" :page-sizes="pageSizes"
:layout="layout" :layout="effectiveLayout"
:total="pager.count" :total="pager.count"
:hide-on-single-page="false" :hide-on-single-page="false"
@size-change="sizeChange" @size-change="sizeChange"
@@ -23,9 +23,10 @@ interface Props {
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
modelValue: () => ({}), modelValue: () => ({}),
pageSizes: () => [15, 20, 30, 40], pageSizes: () => [15, 20, 30, 40]
layout: 'total, sizes, prev, pager, next, jumper'
}) })
const standardLayout = 'total, sizes, prev, pager, next, jumper'
const effectiveLayout = computed(() => props.layout ?? standardLayout)
const emit = defineEmits<{ const emit = defineEmits<{
(event: 'change'): void (event: 'change'): void
@@ -48,3 +49,37 @@ const pageChange = () => {
emit('change') emit('change')
} }
</script> </script>
<style lang="scss">
// A sidebar, dialog or split view can leave less room than the viewport.
:root[data-admin-ui='v2'] .zyt-pagination {
container: zyt-pages / inline-size;
width: 100%;
min-width: 0;
> .el-pagination { justify-content: flex-end; flex-wrap: wrap; }
}
@container zyt-pages (max-width: 740px) {
.zyt-pagination > .el-pagination {
--el-pagination-item-gap: 0px;
gap: 6px;
.el-pagination__rightwrapper, .el-pager { max-width: 100%; flex-wrap: wrap; }
.el-pager { display: flex; justify-content: center; }
// The classic stylesheet hides these slots on mobile. Keep only the
// slots actually requested by this instance's layout.
.el-pagination__sizes, .el-pagination__jump { display: inline-flex !important; }
}
// Only our default order gets explicit rows. Custom layouts keep their DOM order.
.zyt-pagination--standard > .el-pagination {
display: grid;
grid-template-columns: 32px repeat(2, minmax(0, 1fr)) 32px;
column-gap: 0;
max-width: 360px;
margin-inline-start: auto;
.el-pagination__total, .el-pagination__sizes, .el-pager { grid-column: span 2; }
.el-pagination__total { white-space: normal; overflow-wrap: anywhere; }
.el-pagination__sizes { justify-self: end; max-width: 100%; }
.el-pagination__sizes .el-select { max-width: 100%; }
.el-pagination__jump { grid-column: 1 / -1; justify-self: end; }
}
}
</style>
@@ -0,0 +1,33 @@
<template>
<aside v-if="failedRoute" class="route-load-notice" aria-label="页面加载提示">
<div role="status">
<strong>页面未能打开</strong>
<p>当前页面已保留。请检查网络后重试;如需刷新,请先保存正在填写的内容。</p>
</div>
<div class="notice-actions">
<el-button size="small" @click="reportRouteLoad()">关闭提示</el-button>
<el-button size="small" type="primary" @click="retry">重试打开</el-button>
</div>
</aside>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { failedRoute, reportRouteLoad } from '@/utils/route-load-notice'
const router = useRouter()
function retry() {
const target = failedRoute.value
if (target) void router.push(target).catch(() => { /* router.onError owns the feedback */ })
}
</script>
<style scoped>
.route-load-notice {
position: fixed; z-index: 2050; inset-inline-end: 16px; bottom: max(16px, env(safe-area-inset-bottom));
width: min(360px, calc(100vw - 32px)); padding: 16px; border: 1px solid var(--el-border-color);
border-radius: var(--zyt-radius, 10px); color: var(--el-text-color-primary);
background: var(--el-bg-color-overlay); box-shadow: var(--el-box-shadow-light);
}
.route-load-notice p { margin: 4px 0 12px; color: var(--el-text-color-regular); font-size: 13px; }
.notice-actions { display: flex; justify-content: flex-end; gap: 8px; }
.notice-actions .el-button + .el-button { margin: 0; }
</style>
+85
View File
@@ -0,0 +1,85 @@
import { onActivated, onDeactivated, onMounted, onScopeDispose, shallowRef } from 'vue'
type RGB = [number, number, number]
const unpack = (hex: string): RGB => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)) as RGB
const pack = (c: number[]) => '#' + c.map(n => Math.round(n).toString(16).padStart(2, '0')).join('')
const mix = (a: string, b: string, weight: number) => {
const left = unpack(a), right = unpack(b)
return pack(left.map((v, i) => v + (right[i] - v) * weight))
}
const luminance = (hex: string) => {
const [r, g, b] = unpack(hex).map(n => {
const x = n / 255
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4
})
return r * 0.2126 + g * 0.7152 + b * 0.0722
}
const legible = (color: string, bg: string, ink: string, minimum: number) => {
const s = luminance(bg)
for (let i = 0; i <= 64; i++) {
const value = i ? mix(color, ink, i / 64) : color
const l = luminance(value)
if ((Math.max(l, s) + .05) / (Math.min(l, s) + .05) >= minimum) return value
}
return ink
}
function concrete(value: string, fallback: string) {
const str = value.trim()
if (/^#[\da-f]{6}$/i.test(str)) return str.toLowerCase()
if (/^#[\da-f]{3}$/i.test(str)) return '#' + [...str.slice(1)].map(c => c + c).join('').toLowerCase()
const rgb = str.match(/^rgb\(\s*(\d+)\s*[, ]\s*(\d+)\s*[, ]\s*(\d+)\s*\)$/i)
return rgb && rgb.slice(1).every(x => +x <= 255) ? pack(rgb.slice(1).map(Number)) : fallback
}
// Canvas doesn't inherit CSS variables: resolve the active screen theme at the boundary.
export function statsChartPalette(read: (key: string) => string, dark: boolean) {
const get = (key: string, fallback: string) => concrete(read(key), fallback)
const surface = get('--zyt-surface', dark ? '#161618' : '#ffffff')
const ink = get('--zyt-ink', dark ? '#e3e3e8' : '#323251')
const text = get('--zyt-text', dark ? '#ababba' : '#4d5875')
const accent = get('--el-color-primary', '#5d87ff')
return {
dark, accent, surface, ink, text,
accentInk: legible(accent, surface, ink, 3),
accentText: legible(accent, surface, ink, 4.5),
muted: legible(get('--zyt-muted', text), surface, ink, 4.5),
soft: get('--zyt-accent-soft', mix(surface, accent, dark ? .19 : .10)),
grid: mix(surface, text, dark ? .20 : .14),
border: get('--zyt-border', mix(surface, text, .25))
}
}
export function useStatsChartPalette() {
const palette = shallowRef<ReturnType<typeof statsChartPalette> | null>(null)
let observer: MutationObserver | undefined
let paletteSheet: Element | null = null
function refresh() {
const root = document.documentElement
// Settings writes the accent into a stylesheet, not the root's inline style.
const sheet = document.getElementById('art-theme-vars')
if (sheet && sheet !== paletteSheet && observer) {
observer.observe(sheet, { childList: true })
paletteSheet = sheet
}
if (root.dataset.adminUi !== 'v2') { palette.value = null; return }
const css = getComputedStyle(root)
const next = statsChartPalette(key => css.getPropertyValue(key), root.classList.contains('dark'))
const previous = palette.value
if (!previous || (Object.keys(next) as (keyof typeof next)[]).some(key => previous[key] !== next[key])) {
palette.value = next
}
}
function start() {
if (observer || typeof document === 'undefined') return
observer = new MutationObserver(refresh)
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['style', 'class', 'data-admin-ui'] })
observer.observe(document.head, { childList: true })
refresh()
}
function stop() { observer?.disconnect(); observer = undefined; paletteSheet = null }
onMounted(start)
onActivated(start)
onDeactivated(stop)
onScopeDispose(stop)
return palette
}
@@ -26,17 +26,17 @@ useWatchRoute((route) => {
.app-breadcrumb { .app-breadcrumb {
:deep(.el-breadcrumb__item) { :deep(.el-breadcrumb__item) {
.el-breadcrumb__inner { .el-breadcrumb__inner {
color: #303133; color: var(--zyt-text, #303133);
font-weight: 500; font-weight: 500;
} }
&:last-child .el-breadcrumb__inner { &:last-child .el-breadcrumb__inner {
color: #303133; color: var(--zyt-ink, #303133);
} }
} }
:deep(.el-breadcrumb__separator) { :deep(.el-breadcrumb__separator) {
color: #606266; color: var(--zyt-muted, #606266);
} }
} }
</style> </style>
@@ -1,16 +1,22 @@
<template> <template>
<div class="fold h-full cursor-pointer flex items-center px-2" @click="toggleCollapsed"> <button
type="button"
class="fold h-full cursor-pointer flex items-center px-2"
:aria-label="isCollapsed ? '展开菜单' : '收起菜单'"
:title="isCollapsed ? '展开菜单' : '收起菜单'"
:aria-expanded="!isCollapsed"
@click="toggleCollapsed"
>
<icon :name="`local-icon-${isCollapsed ? 'expand' : 'collapse'}`" :size="18" /> <icon :name="`local-icon-${isCollapsed ? 'expand' : 'collapse'}`" :size="18" />
</div> </button>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import useAppStore from '@/stores/modules/app' import useAppStore from '@/stores/modules/app'
import useSettingStore from '@/stores/modules/setting'
const appStore = useAppStore() const appStore = useAppStore()
const settings = useSettingStore()
const isCollapsed = computed(() => appStore.isCollapsed) const isCollapsed = computed(() => appStore.isCollapsed)
// 折叠展开菜单 const toggleCollapsed = () => appStore.toggleHeaderCollapsed(settings.adminUi)
const toggleCollapsed = () => {
appStore.toggleCollapsed()
}
</script> </script>
@@ -3,25 +3,32 @@
<div class="navbar"> <div class="navbar">
<div class="flex-1 flex"> <div class="flex-1 flex">
<div class="navbar-item"> <div class="navbar-item">
<el-tooltip <fold />
class="box-item"
effect="dark"
:content="isCollapsed ? '展开菜单' : '收起菜单'"
placement="bottom"
>
<fold />
</el-tooltip>
</div> </div>
<div class="navbar-item"> <div class="navbar-item">
<el-tooltip class="box-item" effect="dark" content="刷新" placement="bottom"> <refresh />
<refresh />
</el-tooltip>
</div> </div>
<div class="flex items-center px-2" v-if="!isMobile && settingStore.showCrumb"> <div class="flex items-center px-2" v-if="!isMobile && settingStore.showCrumb">
<breadcrumb /> <breadcrumb />
</div> </div>
</div> </div>
<div class="flex"> <div class="flex items-center">
<button
v-if="!liveNative"
class="admin-ui-toggle"
type="button"
data-admin-ui-toggle
aria-label="新版界面"
:aria-pressed="settingStore.adminUi === 'v2'"
:title="settingStore.adminUi === 'v2' ? '切回旧版界面' : '切换至新版界面'"
@click="settingStore.toggleAdminUi()"
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" width="15" height="15">
<rect x="2" y="3" width="12" height="10" rx="2" stroke="currentColor" stroke-width="1.4" />
<path d="M6 3v10m2-7h4" stroke="currentColor" stroke-width="1.4" />
</svg>
{{ settingStore.adminUi === 'v2' ? '切回旧版' : '体验新版' }}
</button>
<div class="navbar-item" v-if="!isMobile"> <div class="navbar-item" v-if="!isMobile">
<el-tooltip <el-tooltip
class="box-item" class="box-item"
@@ -65,9 +72,9 @@ import MultipleTabs from './multiple-tabs.vue'
import Refresh from './refresh.vue' import Refresh from './refresh.vue'
import UserDropDown from './user-drop-down.vue' import UserDropDown from './user-drop-down.vue'
const liveNative = import.meta.env.MODE === 'live-native'
const appStore = useAppStore() const appStore = useAppStore()
const isMobile = computed(() => appStore.isMobile) const isMobile = computed(() => appStore.isMobile)
const isCollapsed = computed(() => appStore.isCollapsed)
const settingStore = useSettingStore() const settingStore = useSettingStore()
const { isFullscreen } = useFullscreen() const { isFullscreen } = useFullscreen()
</script> </script>
@@ -80,4 +87,23 @@ const { isFullscreen } = useFullscreen()
@apply h-full flex justify-center items-center hover:bg-page; @apply h-full flex justify-center items-center hover:bg-page;
} }
} }
.admin-ui-toggle {
height: 30px;
padding: 0 10px;
display: inline-flex;
align-items: center;
gap: 5px;
margin-inline: 4px;
white-space: nowrap;
font-size: 12px;
font-weight: 600;
color: var(--el-color-primary);
border: 1px solid var(--el-color-primary-light-7);
background: var(--el-color-primary-light-9);
border-radius: 6px;
cursor: pointer;
&:hover { border-color: var(--el-color-primary); }
&:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
}
</style> </style>
@@ -1,25 +1,28 @@
<template> <template>
<div class="app-tabs pl-4 flex bg-body"> <div class="app-tabs pl-4 flex bg-body" :class="{ 'work-tabs--art': art }">
<div class="flex-1 min-w-0"> <div class="work-tabs__lane flex-1 min-w-0">
<el-tabs <el-tabs
:model-value="currentTab" :model-value="currentTab"
:closable="tabsLists.length > 1" :closable="tabsLists.length > 1"
@tab-change="handleChange" @tab-change="handleChange"
@tab-remove="removeTab($event)" @tab-remove="closeTab"
> >
<template v-for="item in tabsLists" :key="item.fullPath"> <el-tab-pane v-for="item in tabsLists" :key="item.fullPath" :name="item.fullPath" :label="item.title">
<el-tab-pane :label="item.title" :name="item.fullPath"></el-tab-pane> <template #label>
</template> <span class="work-tabs__label" :title="item.title">{{ item.title }}</span>
</template>
</el-tab-pane>
</el-tabs> </el-tabs>
</div> </div>
<el-dropdown @command="handleCommand"> <el-dropdown ref="actionsMenu" class="work-tabs__actions" :trigger="art ? 'click' : 'hover'" @command="handleCommand">
<span class="flex items-center px-3"> <button ref="actionsButton" class="work-tabs__trigger flex items-center px-3" type="button"
<icon :size="16" name="el-icon-arrow-down" /> aria-label="标签页操作" title="标签页操作" @keydown.esc.stop.prevent="dismissActions">
</span> <icon :size="art ? 20 : 16" name="el-icon-arrow-down" />
</button>
<template #dropdown> <template #dropdown>
<el-dropdown-menu> <el-dropdown-menu @keydown.esc.capture.stop.prevent="dismissActions">
<el-dropdown-item command="closeCurrent"> 关闭当前 </el-dropdown-item> <el-dropdown-item command="closeCurrent" :disabled="!canCloseCurrent">关闭当前</el-dropdown-item>
<el-dropdown-item command="closeOther"> 关闭其他 </el-dropdown-item> <el-dropdown-item command="closeOther" :disabled="!canCloseCurrent">关闭其他</el-dropdown-item>
<el-dropdown-item command="closeAll"> 关闭全部 </el-dropdown-item> <el-dropdown-item command="closeAll"> 关闭全部 </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</template> </template>
@@ -28,29 +31,48 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { DropdownInstance } from 'element-plus'
import useMultipleTabs from '@/hooks/useMultipleTabs' import useMultipleTabs from '@/hooks/useMultipleTabs'
import { useWatchRoute } from '@/hooks/useWatchRoute' import { useWatchRoute } from '@/hooks/useWatchRoute'
import useTabsStore, { getRouteParams } from '@/stores/modules/multipleTabs' import { getRouteParams } from '@/stores/modules/multipleTabs'
import useSettingStore from '@/stores/modules/setting'
const router = useRouter() const router = useRouter()
const tabsStore = useTabsStore() const settings = useSettingStore()
const actionsMenu = ref<DropdownInstance>()
const actionsButton = ref<HTMLButtonElement>()
const dismissActions = () => {
actionsMenu.value?.handleClose()
actionsButton.value?.focus()
}
const art = computed(() => settings.adminUi === 'v2')
const { removeOtherTab, addTab, removeAllTab, removeTab, tabsLists, currentTab } = useMultipleTabs() const { removeOtherTab, addTab, removeAllTab, removeTab, tabsLists, currentTab } = useMultipleTabs()
useWatchRoute(() => { useWatchRoute(() => {
addTab() addTab()
}) })
const handleChange = (fullPath: any) => { const canCloseCurrent = computed(() =>
const tabItem = tabsStore.tasMap[fullPath] tabsLists.value.length > 1 && tabsLists.value.some(tab => tab.fullPath === currentTab.value)
router.push(getRouteParams(tabItem)) )
const handleChange = (fullPath: string | number) => {
// Removal or a route refresh may notify ElTabs after the pane disappeared.
if (fullPath === currentTab.value) return
const tab = tabsLists.value.find(item => item.fullPath === fullPath)
if (tab) router.push(getRouteParams(tab))
}
const closeTab = (fullPath: string | number) => {
if (tabsLists.value.length > 1 && tabsLists.value.some(item => item.fullPath === fullPath)) {
removeTab(fullPath)
}
} }
const handleCommand = (command: any) => { const handleCommand = (command: string) => {
switch (command) { switch (command) {
case 'closeCurrent': case 'closeCurrent':
removeTab() if (canCloseCurrent.value) removeTab()
break break
case 'closeOther': case 'closeOther':
removeOtherTab() if (canCloseCurrent.value) removeOtherTab()
break break
case 'closeAll': case 'closeAll':
removeAllTab() removeAllTab()
@@ -121,4 +143,53 @@ const handleCommand = (command: any) => {
} }
} }
} }
// ArtWorkTab separates its scrolling 32px chips from a fixed 32px action
// button. Keep Element's tablist, scroll arrows, Delete key and roving focus.
.app-tabs.work-tabs--art {
min-width: 0;
align-items: flex-start;
column-gap: 6px;
.work-tabs__lane { container-type: inline-size; }
.work-tabs__label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
:deep(.el-tabs__item) {
max-width: min(220px, 50vw);
// Leave room for Element's two scroll arrows even on a narrow lane.
max-width: min(220px, calc(100cqi - 52px));
padding: 0 10px !important;
&.is-closable { padding-inline: 12px 8px !important; }
&:focus-visible { outline: 2px solid var(--zyt-primary); outline-offset: -2px; }
.is-icon-close {
flex: 0 0 18px;
width: 18px;
height: 18px;
margin-left: 2px;
font-size: 10px;
color: var(--art-gray-600);
&:hover { background: var(--zyt-hover); color: var(--zyt-ink); }
}
}
.work-tabs__actions { flex: none; }
.work-tabs__trigger {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border: 1px solid var(--zyt-card-border);
border-radius: calc(var(--zyt-radius) / 2.5);
background: var(--zyt-surface);
color: var(--art-gray-700);
cursor: pointer;
&:hover { background: var(--zyt-hover); }
&:focus-visible { outline: 2px solid var(--zyt-primary); outline-offset: -2px; }
}
}
</style> </style>
@@ -1,15 +1,18 @@
<template> <template>
<div class="refresh cursor-pointer h-full flex items-center px-2" @click="refreshView"> <button type="button" class="refresh cursor-pointer h-full flex items-center px-2"
aria-label="刷新当前页面" title="刷新当前页面" @click="refreshView">
<icon name="el-icon-RefreshRight" :size="18" /> <icon name="el-icon-RefreshRight" :size="18" />
</div> </button>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import useAppStore from '@/stores/modules/app' import useAppStore from '@/stores/modules/app'
import useTabsStore from '@/stores/modules/multipleTabs'
const appStore = useAppStore() const appStore = useAppStore()
// 刷新页面 const tabs = useTabsStore()
const route = useRoute()
const refreshView = () => { const refreshView = () => {
appStore.refreshView() if (!tabs.refreshCachedTab(route.fullPath)) appStore.refreshView()
} }
</script> </script>
+36 -8
View File
@@ -1,10 +1,13 @@
<template> <template>
<main class="main-wrap h-full bg-page"> <main class="main-wrap h-full bg-page">
<el-scrollbar> <el-scrollbar>
<div class="px-2 py-4"> <div class="admin-content px-2 py-4">
<router-view v-if="isRouteShow" v-slot="{ Component, route }"> <router-view v-slot="{ Component, route: viewRoute }">
<keep-alive :include="includeList" :max="20"> <keep-alive :include="includeList" :max="20">
<component :is="Component" :key="route.fullPath" /> <component v-if="Component && isRouteShow && currentView.shell" :is="currentView.shell" :key="currentView.id">
<component :is="Component" :key="viewRoute.fullPath" />
</component>
<component v-else-if="Component && isRouteShow" :is="Component" :key="viewRoute.fullPath" />
</keep-alive> </keep-alive>
</router-view> </router-view>
</div> </div>
@@ -13,15 +16,40 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, defineComponent, watch, type Component } from 'vue'
import useAppStore from '@/stores/modules/app' import useAppStore from '@/stores/modules/app'
import useTabsStore from '@/stores/modules/multipleTabs' import useTabsStore from '@/stores/modules/multipleTabs'
import useSettingStore from '@/stores/modules/setting' import useSettingStore from '@/stores/modules/setting'
const appStore = useAppStore() const appStore = useAppStore()
const tabsStore = useTabsStore() const tabs = useTabsStore()
const settingStore = useSettingStore() const settings = useSettingStore()
const route = useRoute()
const isRouteShow = computed(() => appStore.isRouteShow) const isRouteShow = computed(() => appStore.isRouteShow)
const includeList = computed(() => (settingStore.openMultipleTabs ? tabsStore.getCacheTabList : []))
</script>
<style></style> // KeepAlive includes/excludes component names, not URLs. Give each opted-in
// work tab its own transparent, named cache boundary so removing one page
// cannot also evict another page backed by the same Vue component.
const cacheName = (id: number) => 'AdminCachedView' + id
const shells = new Map<number, Component>()
const openIds = computed(() => tabs.tabList.flatMap(tab => tab.cacheId ? [tab.cacheId] : []))
const includeList = computed(() => settings.openMultipleTabs ? openIds.value.map(cacheName) : [])
watch(openIds, ids => {
for (const id of shells.keys()) if (!ids.includes(id)) shells.delete(id)
})
const currentView = computed<{ path: string; id?: number; shell?: Component }>((previous) => {
const path = route.fullPath
const id = tabs.tabList.find(item => item.fullPath === path)?.cacheId
// While the router is leaving a just-closed tab, don't mount a throwaway
// copy of its business page. KeepAlive will prune it after the route commit.
if (!id) return previous?.path === path ? previous : { path }
if (!shells.has(id)) {
shells.set(id, defineComponent({
name: cacheName(id),
setup: (_, { slots }) => () => slots.default?.()[0] ?? null
}))
}
return { path, id, shell: shells.get(id) }
})
</script>
@@ -8,16 +8,28 @@
title="主题设置" title="主题设置"
> >
<div class="h-full flex flex-col"> <div class="h-full flex flex-col">
<div v-if="liveNative" class="setting-item mb-5 flex justify-between items-center">
<span class="text-tx-secondary">界面样式</span>
<el-radio-group v-model="interfaceStyle" size="small" aria-label="界面样式">
<el-radio-button value="legacy">经典</el-radio-button>
<el-radio-button value="v2">新版</el-radio-button>
</el-radio-group>
</div>
<div class="setting-item mb-5"> <div class="setting-item mb-5">
<span class="text-tx-secondary">风格设置</span> <span class="text-tx-secondary">风格设置</span>
<div class="flex mt-4 cursor-pointer"> <div v-if="settingStore.adminUi === 'v2'" class="art-menu-options" role="group" aria-label="菜单风格">
<button v-for="item in artMenuThemes" :key="item.value" type="button"
:aria-label="item.label + '菜单'" :aria-pressed="sideTheme === item.value"
@click="sideTheme = item.value">{{ item.label }}</button>
</div>
<div v-else class="flex mt-4 cursor-pointer">
<div <div
class="mr-4 flex relative text-primary" class="mr-4 flex relative text-primary"
v-for="item in sideThemeList" v-for="item in sideThemeList"
:key="item.type" :key="item.type"
@click="sideTheme = item.type" @click="sideTheme = item.type"
> >
<img :src="item.image" width="52" height="36" /> <img :src="item.image" :alt="item.type === 'dark' ? '深色菜单' : '浅色菜单'" width="52" height="36" />
<icon <icon
v-if="sideTheme == item.type" v-if="sideTheme == item.type"
class="icon-select" class="icon-select"
@@ -93,14 +105,23 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { useDark, useToggle } from '@vueuse/core'
import theme_dark from '@/assets/images/theme_black.png' import theme_dark from '@/assets/images/theme_black.png'
import theme_light from '@/assets/images/theme_white.png' import theme_light from '@/assets/images/theme_white.png'
import useSettingStore from '@/stores/modules/setting' import useSettingStore, { artMainColors, useAdminDark } from '@/stores/modules/setting'
const liveNative = import.meta.env.MODE === 'live-native'
const settingStore = useSettingStore() const settingStore = useSettingStore()
const predefineColors = ref(['#409EFF', '#28C76F', '#EA5455', '#FF9F43', '#01CFE8', '#4A5DFF']) const interfaceStyle = computed({
get: () => settingStore.adminUi,
set(value: 'legacy' | 'v2') {
if (value !== settingStore.adminUi) settingStore.toggleAdminUi()
}
})
const predefineColors = computed(() => settingStore.adminUi === 'v2' ? artMainColors :
['#409EFF', '#28C76F', '#EA5455', '#FF9F43', '#01CFE8', '#4A5DFF'])
const artMenuThemes = [
{ value: 'design', label: '设计' }, { value: 'dark', label: '深色' }, { value: 'light', label: '浅色' }
]
const sideThemeList = [ const sideThemeList = [
{ {
type: 'dark', type: 'dark',
@@ -177,9 +198,8 @@ const theme = computed({
set(value) { set(value) {
settingStore.setSetting({ settingStore.setSetting({
key: 'theme', key: 'theme',
value value: value || (settingStore.adminUi === 'v2' ? artMainColors[0] : settingStore.theme)
}) })
themeChange()
} }
}) })
@@ -207,19 +227,11 @@ const showCrumb = computed({
} }
}) })
const isDark = useDark() const isDark = useAdminDark()
const themeChange = () => { const toggleDark = () => { isDark.value = !isDark.value }
settingStore.setTheme(isDark.value)
}
const toggleDark = () => {
useToggle(isDark)()
themeChange()
}
const resetTheme = () => { const resetTheme = () => {
isDark.value = false if (settingStore.adminUi === 'legacy') isDark.value = false
settingStore.resetTheme() settingStore.resetTheme()
themeChange()
} }
</script> </script>
@@ -0,0 +1,118 @@
<template>
<ul class="dual-branch">
<li v-for="node in nodes" :key="node.key">
<component
:is="node.children.length ? 'button' : AppLink"
:type="node.children.length ? 'button' : undefined"
:to="node.children.length ? undefined : node.target"
:rel="node.external ? 'noopener noreferrer' : undefined"
class="dual-row"
:class="{ 'is-active': node.key === leafKey }"
:style="{ '--branch-depth': depth }"
:title="node.title"
:aria-label="node.title"
:aria-current="node.key === leafKey ? 'page' : undefined"
:aria-expanded="node.children.length ? opened.includes(node.key) : undefined"
@click="node.children.length && toggle(node.key)"
>
<icon v-if="node.icon" :name="node.icon" :size="18" class="dual-row-icon" aria-hidden="true" />
<span class="dual-label">{{ node.title }}</span>
<svg v-if="node.children.length" class="dual-chevron" aria-hidden="true"
viewBox="0 0 16 16" width="14" height="14" fill="none">
<path d="m4 6 4 4 4-4" stroke="currentColor" stroke-width="1.5"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</component>
<dual-branch
v-if="node.children.length && opened.includes(node.key)"
:nodes="node.children"
:depth="depth + 1"
:leaf-key="leafKey"
:ancestor-keys="ancestorKeys"
:route-key="routeKey"
:unique="unique"
/>
</li>
</ul>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import AppLink from '@/components/app-link/index.vue'
import type { DualNode } from './dual-model'
const props = withDefaults(defineProps<{
nodes: DualNode[]
leafKey?: string
ancestorKeys: string[]
routeKey: string
unique: boolean
depth?: number
}>(), { depth: 0 })
// Each list owns its sibling disclosures. Router changes reveal the active
// chain (including on direct load); a user can still close that chain in place.
const opened = ref<string[]>([])
watch([() => props.ancestorKeys, () => props.routeKey, () => props.unique], () => {
const ancestor = props.nodes.find(node => node.children.length && props.ancestorKeys.includes(node.key))
if (ancestor) {
if (props.unique) opened.value = [ancestor.key]
else if (!opened.value.includes(ancestor.key)) opened.value.push(ancestor.key)
} else if (props.unique) {
opened.value = []
}
}, { immediate: true })
function toggle(key: string) {
if (opened.value.includes(key)) opened.value = opened.value.filter(item => item !== key)
else if (props.unique) opened.value = [key]
else opened.value.push(key)
}
</script>
<style scoped>
.dual-branch { margin: 0; padding: 0; list-style: none; }
.dual-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
height: 42px;
margin-bottom: 4px;
padding-inline: calc(12px + min(3, var(--branch-depth, 0)) * 14px) 12px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--zyt-nav-text);
font-size: 14px;
line-height: 1.35;
text-align: start;
text-decoration: none;
cursor: pointer;
}
.dual-row:hover { background: var(--zyt-nav-hover); }
.dual-row.is-active {
background: var(--zyt-nav-active);
color: var(--zyt-nav-selected);
}
.dual-row-icon { flex: none; color: var(--zyt-nav-icon); }
.dual-row.is-active .dual-row-icon { color: inherit; }
.dual-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dual-chevron {
flex: none;
color: var(--zyt-nav-arrow);
transition: transform .16s ease;
}
.dual-row[aria-expanded='true'] > .dual-chevron { transform: rotate(180deg); }
.dual-row:focus-visible { outline: 2px solid var(--zyt-nav-selected); outline-offset: -2px; }
html:not(.dark) .side--light .dual-row.is-active { box-shadow: inset 3px 0 var(--zyt-primary); }
@media (prefers-reduced-motion: reduce) { .dual-chevron { transition: none; } }
</style>
@@ -0,0 +1,154 @@
import {
parseQuery,
type LocationQuery,
type RouteLocationNormalizedLoaded,
type RouteRecordRaw
} from 'vue-router'
import { MenuEnum } from '@/enums/appEnums'
import { getNormalPath, objectToQuery } from '@/utils/util'
import { isExternal } from '@/utils/validate'
export interface DualNode {
key: string
path: string
target: string
title: string
icon?: string
children: DualNode[]
external: boolean
}
function resolvePath(path: string, parent?: string) {
if (parent === undefined || isExternal(path)) return path
// The read-only router assigns absolute IDs even to deeply nested entries.
if (import.meta.env.MODE === 'live-readonly' && path.startsWith('/nav/')) return path
return getNormalPath(`${parent}/${path}`)
}
function menuTarget(path: string, query: unknown) {
let suffix = ''
if (typeof query === 'string' && query) {
try {
suffix = objectToQuery(JSON.parse(query))
} catch {
suffix = query
}
} else if (query && typeof query === 'object') {
suffix = objectToQuery(query)
}
suffix = suffix.replace(/^\?/, '')
return suffix ? `${path}${path.includes('?') ? '&' : '?'}${suffix}` : path
}
/** Project only the current account's supplied menu tree; permission strings are not new routes. */
export function buildDualMenu(routes: RouteRecordRaw[]): DualNode[] {
function visit(records: RouteRecordRaw[], parentPath?: string, parentKey = ''): DualNode[] {
const nodes: DualNode[] = []
const occurrences = new Map<string, number>()
for (const route of records) {
const meta = route.meta
if (meta?.hidden || meta?.type === MenuEnum.BUTTON) continue
const path = resolvePath(route.path, parentPath)
const target = menuTarget(path, meta?.query)
// Index children share their parent's path; query variants also need distinct keys.
const count = occurrences.get(target) || 0
occurrences.set(target, count + 1)
const key = `${parentKey}/${encodeURIComponent(target)}:${count}`
const children = visit(route.children || [], path, key)
// A catalogue is not an authorized landing page. A real page may have hidden details.
if (
!children.length &&
(meta?.type === MenuEnum.CATALOGUE ||
(route.children?.length && meta?.type !== MenuEnum.MENU))
)
continue
nodes.push({
key,
path,
target,
title: meta?.title || '',
icon: meta?.icon,
children,
external: isExternal(path)
})
}
return nodes
}
return visit(routes)
}
/** Entering a module must never open an external site as a side effect. */
export function firstDualLeaf(node: DualNode): DualNode | undefined {
if (!node.children.length) return node.external ? undefined : node
for (const child of node.children) {
const leaf = firstDualLeaf(child)
if (leaf) return leaf
}
}
function splitLocation(location: string) {
const href = location.split('#', 1)[0]
const q = href.indexOf('?')
const path = q < 0 ? href : href.slice(0, q)
return {
path: path.replace(/\/+$/, '') || '/',
query: q < 0 ? undefined : parseQuery(href.slice(q + 1))
}
}
// Compare decoded Vue Router values, not query-string order. Extra page filters are allowed.
function matchQuery(defaults: LocationQuery, current: LocationQuery) {
const keys = Object.keys(defaults)
const matches = keys.every((key) => {
const expected = defaults[key]
const actual = current[key]
return Array.isArray(expected)
? Array.isArray(actual) &&
expected.length === actual.length &&
expected.every((v, i) => v === actual[i])
: expected === actual
})
if (!matches) return -1
if (keys.length === Object.keys(current).length) return Number.POSITIVE_INFINITY
return keys.length
}
interface DualSelection {
root?: DualNode
leaf?: DualNode
/** Includes the root and every group to expand, never the highlighted leaf. */
ancestors: DualNode[]
}
export function findDualSelection(
roots: DualNode[],
route: RouteLocationNormalizedLoaded
): DualSelection {
const active = splitLocation(route.meta.activeMenu || route.path)
const current = active.query ?? route.query
let selection: DualSelection = { ancestors: [] }
let bestScore = Number.NEGATIVE_INFINITY
function visit(nodes: DualNode[], parents: DualNode[]) {
for (const node of nodes) {
if (node.external) continue
const groups = node.children.length ? [...parents, node] : parents
const target = splitLocation(node.target)
if (target.path === active.path) {
// Empty index leaves take precedence over grouping records at the very same path.
const score = node.children.length ? -2 : matchQuery(target.query || {}, current)
if (score > bestScore) {
bestScore = score
selection = {
root: parents[0] || node,
leaf: node.children.length ? undefined : node,
ancestors: groups
}
}
}
if (node.children.length) visit(node.children, groups)
}
}
visit(roots, [])
return selection
}
@@ -0,0 +1,225 @@
<template>
<div class="dual-sidebar" :class="{ 'dual-sidebar--compact': app.isCollapsed }"
@keydown.space="activateLinkWithSpace">
<nav class="dual-primary" :aria-label="app.isCollapsed ? '折叠菜单' : '一级菜单'">
<app-link v-if="settings.showLogo" class="logo dual-brand" to="/"
:aria-label="brandName ? brandName + ',返回首页' : '返回首页'" :title="brandName || '首页'">
<image-contain class="logo-mark" :height="34" :width="34" fit="contain"
:src="app.config.web_logo" alt="" />
</app-link>
<div v-else class="admin-nav-heading dual-brand" aria-hidden="true">
<svg viewBox="0 0 24 24" width="24" height="24" fill="none">
<path d="M4 6.5h10M4 12h16M4 17.5h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<circle cx="19" cy="6.5" r="2" fill="currentColor"/>
</svg>
</div>
<side-menu v-if="app.isCollapsed"
:nodes="roots" :active-key="selection.leaf?.key"
:is-collapsed="true" :classic="false" :theme="settings.sideTheme"
:unique-opened="settings.isUniqueOpened" />
<ul v-else ref="rootList" class="dual-roots">
<li v-for="root in roots" :key="root.key">
<component
:is="root.children.length ? 'button' : AppLink"
:type="root.children.length ? 'button' : undefined"
:to="root.children.length ? undefined : root.target"
:rel="root.external ? 'noopener noreferrer' : undefined"
class="dual-root"
:class="{ 'is-active': activeRoot?.key === root.key }"
:aria-expanded="root.children.length ? activeRoot?.key === root.key : undefined"
:aria-current="!root.children.length && selection.leaf?.key === root.key ? 'page' : undefined"
:aria-label="root.title"
:title="root.title"
@click="chooseRoot(root)"
>
<span class="dual-root-icon" aria-hidden="true">
<icon v-if="root.icon" :name="root.icon" :size="20" />
<template v-else>{{ Array.from(root.title.trim())[0] }}</template>
</span>
<span class="dual-root-label">{{ root.title }}</span>
</component>
</li>
</ul>
</nav>
<nav v-if="!app.isCollapsed && activeRoot?.children.length" class="dual-secondary"
aria-label="二级菜单" :style="{ width: settings.sideWidth + 'px' }">
<div class="dual-heading" :title="panelHeading">{{ panelHeading }}</div>
<div ref="branchList" class="dual-scroll" :key="activeRoot.key">
<dual-branch
:nodes="activeRoot.children"
:leaf-key="selection.leaf?.key"
:ancestor-keys="ancestorKeys"
:route-key="route.fullPath"
:unique="settings.isUniqueOpened"
/>
</div>
</nav>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter, type RouteRecordRaw } from 'vue-router'
import AppLink from '@/components/app-link/index.vue'
import useAppStore from '@/stores/modules/app'
import useSettingStore from '@/stores/modules/setting'
import DualBranch from './dual-branch.vue'
import SideMenu from './menu.vue'
import { buildDualMenu, findDualSelection, firstDualLeaf, type DualNode } from './dual-model'
const props = defineProps<{ routes: RouteRecordRaw[] }>()
const app = useAppStore()
const settings = useSettingStore()
const router = useRouter()
const route = useRoute()
const roots = computed(() => buildDualMenu(props.routes))
const selection = computed(() => findDualSelection(roots.value, route))
const ancestorKeys = computed(() => selection.value.ancestors.map(node => node.key))
// Only an external-only directory needs a local selection: it has no internal
// destination. Never open an external site while selecting a group or syncing a route.
const externalGroup = ref<string>()
watch([() => route.fullPath, roots], () => { externalGroup.value = undefined })
const activeRoot = computed(() => externalGroup.value
? roots.value.find(node => node.key === externalGroup.value)
: selection.value.root)
const brandName = computed(() => String(app.config.web_name || ''))
const panelHeading = computed(() =>
(settings.showLogo && brandName.value) || activeRoot.value?.title || ''
)
const rootList = ref<HTMLElement>()
const branchList = ref<HTMLElement>()
function revealActiveItems() {
for (const list of [rootList.value, branchList.value]) {
const item = list?.querySelector('.is-active')
if (!list || !item) continue
const row = item.getBoundingClientRect()
const box = list.getBoundingClientRect()
if (row.top < box.top) list.scrollTop += row.top - box.top
else if (row.bottom > box.bottom) list.scrollTop += row.bottom - box.bottom
}
}
onMounted(revealActiveItems)
watch([activeRoot, selection, () => app.isCollapsed], revealActiveItems, { flush: 'post' })
function chooseRoot(node: DualNode) {
if (!node.children.length) {
if (!node.external) externalGroup.value = undefined
return // The AppLink handles normal navigation and modifier-clicks.
}
const leaf = firstDualLeaf(node)
externalGroup.value = leaf ? undefined : node.key
if (leaf) void router.push(leaf.target)
}
function activateLinkWithSpace(event: KeyboardEvent) {
// Buttons already handle both keys natively. Extend anchors with Space
// without intercepting their Enter or modified pointer navigation.
if (!(event.target instanceof HTMLAnchorElement)) return
event.preventDefault()
if (!event.repeat) event.target.click()
}
</script>
<style scoped>
.dual-sidebar {
--rail-width: 80px;
display: flex;
flex: 1 1 0;
min-height: 0;
background: var(--zyt-nav-bg);
color: var(--zyt-nav-text);
}
.dual-sidebar--compact { --rail-width: 64px; }
.dual-primary, .dual-secondary {
display: flex;
flex: none;
flex-direction: column;
min-height: 0;
}
.dual-primary { width: var(--rail-width); }
.dual-sidebar .dual-primary > .dual-brand {
flex: none;
justify-content: center;
width: 100%;
height: var(--navbar-height);
padding: 0;
}
.dual-roots, .dual-scroll {
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: thin;
}
.dual-roots {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 4px 8px 12px;
list-style: none;
scrollbar-width: none; /* Keep icon centers aligned with the logo on scroll. */
}
.dual-roots::-webkit-scrollbar { display: none; }
.dual-root {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 5px;
width: 100%;
height: 60px;
padding: 0 2px;
border: 0;
border-radius: 5px;
background: transparent;
color: var(--zyt-nav-text);
text-align: center;
cursor: pointer;
}
.dual-root:hover { background: var(--zyt-nav-hover); }
.dual-root.is-active {
background: var(--zyt-nav-active);
color: var(--zyt-nav-selected);
}
.dual-root-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
color: var(--zyt-nav-icon);
font-size: 16px;
line-height: 1;
}
.dual-root.is-active .dual-root-icon { color: inherit; }
.dual-root-label, .dual-heading {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dual-root-label { width: 100%; font-size: 12px; line-height: 16px; }
.dual-secondary {
box-sizing: border-box;
border-inline-start: 1px solid var(--zyt-card-border);
}
.dual-heading {
flex: none;
padding-inline: 20px;
color: var(--zyt-nav-title);
font-size: 17px;
font-weight: 600;
line-height: var(--navbar-height);
}
.dual-scroll { padding: 4px 8px 12px; }
.dual-root:focus-visible, .dual-brand:focus-visible {
outline: 2px solid var(--zyt-nav-selected);
outline-offset: -2px;
}
</style>
@@ -0,0 +1,50 @@
import type { MenuInstance } from 'element-plus'
import { nextTick, useId, type Ref } from 'vue'
import type { DualNode } from './dual-model'
/** ElMenu supplies hover, positioning, dismissal and selection. Its vertical
* popup mode doesn't supply keyboard entry, so drive its public open/close API. */
export function useFlyoutKeyboard(
menu: Ref<MenuInstance | undefined>,
activeKey: () => string | undefined,
dismiss: () => void
) {
// Popup children may be teleported outside the nav. Scope IDs to this menu
// instance (the mobile drawer can leave another sidebar mounted).
const prefix = useId()
const id = (node: DualNode) => `nav-${prefix}-${node.key}`
const focus = (node: DualNode) => document.getElementById(id(node))?.focus()
return (node: DualNode, parent?: DualNode) => ({
id: id(node),
tabindex: node.children.length ? 0 : undefined,
'aria-current': node.key === activeKey() ? 'page' as const : undefined,
onClick: node.children.length ? undefined : dismiss,
onKeydown(event: KeyboardEvent) {
// A nested, non-teleported popup also bubbles through its parent
// directory. Only the focused row owns this keystroke.
if (event.target !== event.currentTarget) return
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
const trigger = event.currentTarget as HTMLElement
const key = event.key
if (node.children.length && ['ArrowRight', 'Enter', ' '].includes(key)) {
menu.value?.open(node.key)
void nextTick(() => focus(node.children[0]))
} else if (key === 'Escape' || key === 'ArrowLeft') {
const group = trigger.getAttribute('aria-expanded') === 'true' ? node : parent
if (!group) return
menu.value?.close(group.key)
focus(group)
} else if (!node.children.length && key === ' ') {
trigger.click()
} else {
return
}
event.preventDefault()
event.stopPropagation()
}
})
}
export type FlyoutKeyboard = ReturnType<typeof useFlyoutKeyboard>
@@ -27,7 +27,8 @@ const showMenuDrawer = computed({
return !appStore.isCollapsed && isMobile.value return !appStore.isCollapsed && isMobile.value
}, },
set(value) { set(value) {
appStore.toggleCollapsed(!value) // A closing mobile drawer may emit after the desktop sidebar is restored.
if (isMobile.value) appStore.toggleCollapsed(!value)
} }
}) })
@@ -1,12 +1,12 @@
<template> <template>
<div class="logo" @click="handleClick"> <div class="logo" @click="handleClick">
<image-contain :width="szie" :height="szie" :src="config.web_logo" /> <image-contain class="logo-mark" :width="size" :height="size" :src="config.web_logo" />
<transition name="title-width"> <transition name="title-width">
<div <div
v-show="showTitle" v-show="showTitle"
class="logo-title overflow-hidden whitespace-nowrap" class="logo-title overflow-hidden whitespace-nowrap"
:class="{ 'text-white': theme == ThemeEnum.DARK }" :class="{ 'text-white': theme == ThemeEnum.DARK }"
:style="{ left: `${szie + 16}px` }" :style="{ left: `${size + 16}px` }"
> >
<overflow-tooltip <overflow-tooltip
:content="title || config.web_name" :content="title || config.web_name"
@@ -25,7 +25,7 @@ import { ThemeEnum } from '@/enums/appEnums'
import useAppStore from '@/stores/modules/app' import useAppStore from '@/stores/modules/app'
defineProps({ defineProps({
szie: { type: Number, default: 34 }, size: { type: Number, default: 34 },
title: { type: String }, title: { type: String },
theme: { type: String }, theme: { type: String },
showTitle: { type: Boolean, default: true } showTitle: { type: Boolean, default: true }
@@ -66,4 +66,17 @@ const handleClick = () => {
opacity: 0; opacity: 0;
} }
} }
:root[data-admin-ui='v2'] .logo {
// Let the menu, not the intrinsic width of the configured name, size the sidebar.
contain: inline-size;
.logo-mark {
flex: none;
:deep(.el-image__inner) { object-fit: contain; }
}
.logo-title {
flex: 1;
min-width: 0;
}
}
</style> </style>
@@ -1,34 +1,50 @@
<template> <template>
<template v-if="!route.meta?.hidden"> <template v-if="node || !route?.meta?.hidden">
<app-link v-if="!hasShowChild" :to="`${routePath}?${queryStr}`"> <app-link v-if="!hasShowChild" :to="node?.target ?? menuTarget" :class="{ 'admin-nav-link': art }"
<el-menu-item :index="routePath"> v-bind="flyoutAttrs" :aria-label="node?.title" :rel="node?.external ? 'noopener noreferrer' : undefined">
<el-menu-item :index="node?.key ?? routePath" :aria-label="art ? title : undefined">
<icon <icon
class="menu-item-icon" class="menu-item-icon"
:size="16" :size="art ? 20 : 16"
v-if="routeMeta?.icon" v-if="iconName"
:name="routeMeta?.icon" :name="iconName"
/> />
<i v-else-if="art" class="menu-item-icon admin-nav-icon--empty" aria-hidden="true"
:data-initial="titleInitial" />
<template #title> <template #title>
<span>{{ routeMeta?.title }}</span> <span class="menu-name" :title="art ? title : undefined">{{ title }}</span>
</template> </template>
</el-menu-item> </el-menu-item>
</app-link> </app-link>
<el-sub-menu v-else :index="routePath" :popper-class="popperClass"> <el-sub-menu v-else v-bind="flyoutAttrs" :index="node?.key ?? routePath" :popper-class="popperClass"
:aria-label="art ? title : undefined">
<template #title> <template #title>
<icon <icon
class="menu-item-icon" class="menu-item-icon"
:size="16" :size="art ? 20 : 16"
v-if="routeMeta?.icon" v-if="iconName"
:name="routeMeta?.icon" :name="iconName"
/> />
<span>{{ routeMeta?.title }}</span> <i v-else-if="art" class="menu-item-icon admin-nav-icon--empty" aria-hidden="true"
:data-initial="titleInitial" />
<span class="menu-name" :title="art ? title : undefined">{{ title }}</span>
</template> </template>
<menu-item
v-for="child in node?.children"
:key="child.key"
:node="child"
:parent-node="node"
:flyout="flyout"
:popper-class="popperClass"
:art="art"
/>
<menu-item <menu-item
v-for="item in route?.children" v-for="item in route?.children"
:key="resolvePath(item.path)" :key="resolvePath(item.path)"
:route="item" :route="item"
:route-path="resolvePath(item.path)" :route-path="resolvePath(item.path)"
:popper-class="popperClass" :popper-class="popperClass"
:art="art"
/> />
</el-sub-menu> </el-sub-menu>
</template> </template>
@@ -40,24 +56,38 @@ import type { RouteRecordRaw } from 'vue-router'
import { getNormalPath, objectToQuery } from '@/utils/util' import { getNormalPath, objectToQuery } from '@/utils/util'
import { isExternal } from '@/utils/validate' import { isExternal } from '@/utils/validate'
import type { DualNode } from './dual-model'
import type { FlyoutKeyboard } from './flyout-keyboard'
interface Props { interface Props {
route: RouteRecordRaw node?: DualNode
routePath: string parentNode?: DualNode
flyout?: FlyoutKeyboard
route?: RouteRecordRaw
routePath?: string
popperClass: string popperClass: string
art?: boolean
} }
const props = defineProps<Props>() const props = withDefaults(defineProps<Props>(), { routePath: '' })
const flyoutAttrs = computed(() =>
props.node ? props.flyout?.(props.node, props.parentNode) : undefined
)
const hasShowChild = computed(() => { const hasShowChild = computed(() => {
const children: RouteRecordRaw[] = props.route.children ?? [] if (props.node) return !!props.node.children.length
const children: RouteRecordRaw[] = props.route?.children ?? []
return !!children.filter((item) => !item.meta?.hidden).length return !!children.filter((item) => !item.meta?.hidden).length
}) })
const routeMeta = computed(() => { const title = computed(() => props.node?.title ?? props.route?.meta?.title)
return props.route.meta const iconName = computed(() => props.node?.icon ?? props.route?.meta?.icon)
}) const titleInitial = computed(() => Array.from(String(title.value || '').trim())[0])
const resolvePath = (path: string) => { const resolvePath = (path: string) => {
// The online preview uses generated absolute item IDs to preserve arbitrary
// server menu nesting without ever routing by untrusted component strings.
if (import.meta.env.MODE === 'live-readonly' && path.startsWith('/nav/')) return path
if (isExternal(path)) { if (isExternal(path)) {
return path return path
} }
@@ -65,7 +95,7 @@ const resolvePath = (path: string) => {
return newPath return newPath
} }
const queryStr = computed<string>(() => { const queryStr = computed<string>(() => {
const query = props.route.meta?.query as string const query = props.route?.meta?.query as string
try { try {
const queryObj = JSON.parse(query) const queryObj = JSON.parse(query)
return objectToQuery(queryObj) return objectToQuery(queryObj)
@@ -75,6 +105,10 @@ const queryStr = computed<string>(() => {
return query return query
} }
}) })
const menuTarget = computed(() => {
const q = String(queryStr.value || '').replace(/^\?/, '')
return q ? `${props.routePath}${props.routePath.includes('?') ? '&' : '?'}${q}` : props.routePath
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.el-menu-item, .el-menu-item,
@@ -1,24 +1,36 @@
<template> <template>
<div <div
class="menu flex-1 min-h-0" class="menu flex-1 min-h-0"
:class="themeClass" :class="[themeClass, classic ? 'menu--classic' : 'admin-nav-tree']"
:style="isCollapsed ? '' : `--aside-width: ${width}px`" :style="isCollapsed ? '' : `--aside-width: ${width}px`"
> >
<el-scrollbar> <el-scrollbar>
<el-menu <el-menu
ref="menu"
v-bind="config" v-bind="config"
:default-active="activeMenu" :default-active="activeMenu"
:collapse="isCollapsed" :collapse="isCollapsed"
mode="vertical" mode="vertical"
:unique-opened="uniqueOpened" :unique-opened="uniqueOpened"
@select="$emit('select')" @open="trackOpen"
@close="openGroups.delete($event)"
@select="handleSelect"
> >
<menu-item
v-for="node in nodes"
:key="node.key"
:node="node"
:flyout="flyout"
:art="true"
:popper-class="popperClass"
/>
<menu-item <menu-item
v-for="route in routes" v-for="route in routes"
:key="route.path" :key="route.path"
:route="route" :route="route"
:route-path="route.path" :route-path="route.path"
:popper-class="themeClass" :art="!classic"
:popper-class="popperClass"
/> />
</el-menu> </el-menu>
</el-scrollbar> </el-scrollbar>
@@ -26,12 +38,18 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { PropType } from 'vue' import type { MenuInstance } from 'element-plus'
import { computed, nextTick, ref, type PropType } from 'vue'
import type { RouteRecordRaw } from 'vue-router' import type { RouteRecordRaw } from 'vue-router'
import type { DualNode } from './dual-model'
import { useFlyoutKeyboard } from './flyout-keyboard'
import MenuItem from './menu-item.vue' import MenuItem from './menu-item.vue'
const props = defineProps({ const props = defineProps({
classic: { type: Boolean, default: true },
nodes: Array as PropType<DualNode[]>,
activeKey: String,
routes: { routes: {
type: Object as PropType<RouteRecordRaw[]> type: Object as PropType<RouteRecordRaw[]>
}, },
@@ -55,16 +73,38 @@ const props = defineProps({
} }
}) })
defineEmits(['select']) const emit = defineEmits(['select'])
const menu = ref<MenuInstance>()
const openGroups = new Set<string>()
const trackOpen = (key: string) => { if (props.nodes) openGroups.add(key) }
function dismissFlyouts() {
// The anchor can be activated directly (including assistive technology
// and new-tab links), bypassing ElMenuItem's native select handler.
for (const key of openGroups) menu.value?.close(key)
openGroups.clear()
}
const flyout = useFlyoutKeyboard(menu, () => props.activeKey, dismissFlyouts)
const route = useRoute() const route = useRoute()
const activeMenu = computed<string>(() => route.meta?.activeMenu || route.path) const activeMenu = computed<string>(() =>
props.nodes ? props.activeKey ?? '' : route.meta?.activeMenu || route.path
)
function handleSelect() {
emit('select')
// ElMenu closes its popups on select. Keep the highlight on the actual page
// if a link opens a new tab instead of changing the current route.
if (props.nodes && activeMenu.value) void nextTick(() => menu.value?.updateActiveIndex(activeMenu.value))
}
const themeClass = computed(() => `theme-${props.theme}`) const themeClass = computed(() => `theme-${props.theme}`)
// Teleported flyouts do not inherit the palette from .side.
const popperClass = computed(() =>
props.classic ? themeClass.value : `admin-nav-popper side--${props.theme}`
)
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.menu { .menu {
&.theme-dark { &.menu--classic.theme-dark {
.el-menu { .el-menu {
:deep(.el-menu-item) { :deep(.el-menu-item) {
&.is-active { &.is-active {
@@ -78,7 +118,7 @@ const themeClass = computed(() => `theme-${props.theme}`)
} }
} }
} }
&.theme-light { &.menu--classic.theme-light {
:deep(.el-menu) { :deep(.el-menu) {
.el-menu-item { .el-menu-item {
border-color: transparent; border-color: transparent;
@@ -1,15 +1,26 @@
<template> <template>
<div class="side" :style="sideStyle"> <div class="side" :class="['side--' + sideTheme, { 'side--collapsed': isCollapsed }]" :style="sideStyle">
<side-logo v-if="settingStore.showLogo" :show-title="!isCollapsed" :theme="sideTheme" /> <dual-sidebar v-if="useDualSidebar" :routes="routes" />
<side-menu <template v-else>
:routes="routes" <side-logo v-if="settingStore.showLogo" :show-title="!isCollapsed" :theme="sideTheme" />
:is-collapsed="isCollapsed" <div v-else-if="settingStore.adminUi === 'v2'" class="admin-nav-heading" aria-hidden="true">
:width="settingStore.sideWidth" <svg viewBox="0 0 24 24" fill="none" width="24" height="24">
:unique-opened="settingStore.isUniqueOpened" <path d="M4 6.5h10M4 12h16M4 17.5h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
:config="menuProp" <circle cx="19" cy="6.5" r="2" fill="currentColor"/>
:theme="sideTheme" </svg>
@select="handleSelect" <span v-if="!isCollapsed">工作导航</span>
/> </div>
<side-menu
:routes="routes"
:is-collapsed="isCollapsed"
:width="settingStore.sideWidth"
:unique-opened="settingStore.isUniqueOpened"
:config="menuProp"
:theme="sideTheme"
:classic="settingStore.adminUi === 'legacy'"
@select="handleSelect"
/>
</template>
</div> </div>
</template> </template>
@@ -18,6 +29,7 @@ import useAppStore from '@/stores/modules/app'
import useSettingStore from '@/stores/modules/setting' import useSettingStore from '@/stores/modules/setting'
import useUserStore from '@/stores/modules/user' import useUserStore from '@/stores/modules/user'
import DualSidebar from './dual-sidebar.vue'
import SideLogo from './logo.vue' import SideLogo from './logo.vue'
import SideMenu from './menu.vue' import SideMenu from './menu.vue'
@@ -31,19 +43,22 @@ const isCollapsed = computed(() => {
}) })
const settingStore = useSettingStore() const settingStore = useSettingStore()
// The fixture and read-only preview clients retain their own menu contracts.
const useDualSidebar = computed(() =>
settingStore.adminUi === 'v2' && !appStore.isMobile &&
!['live-readonly', 'local-preview'].includes(import.meta.env.MODE)
)
const sideTheme = computed(() => settingStore.sideTheme) const sideTheme = computed(() => settingStore.sideTheme)
const userStore = useUserStore() const userStore = useUserStore()
const routes = computed(() => userStore.routes) const routes = computed(() => userStore.routes)
const sideStyle = computed(() => { const sideStyle = computed(() => settingStore.adminUi === 'legacy' && sideTheme.value === 'dark'
return sideTheme.value == 'dark' ? { '--side-dark-color': settingStore.sideDarkColor }
? { : undefined)
'--side-dark-color': settingStore.sideDarkColor
}
: ''
})
const menuProp = computed(() => { const menuProp = computed(() => {
// In v2 the root tokens also style the collapsed menu's teleported popup.
if (settingStore.adminUi === 'v2') return {}
return { return {
backgroundColor: sideTheme.value == 'dark' ? settingStore.sideDarkColor : '', backgroundColor: sideTheme.value == 'dark' ? settingStore.sideDarkColor : '',
textColor: sideTheme.value == 'dark' ? 'var(--el-color-white)' : '', textColor: sideTheme.value == 'dark' ? 'var(--el-color-white)' : '',
@@ -64,4 +79,18 @@ const handleSelect = () => {
@apply border-r border-br-light h-full flex flex-col; @apply border-r border-br-light h-full flex flex-col;
background-color: var(--side-dark-color, var(--el-bg-color)); background-color: var(--side-dark-color, var(--el-bg-color));
} }
// The menu sets the rail width. Center either mark within that same content
// box (excluding the sidebar border), without the expanded header's 22px inset.
:root[data-admin-ui='v2'] .side--collapsed {
> :is(.logo, .admin-nav-heading) {
justify-content: center;
padding-inline: 0;
gap: 0;
}
// v-show keeps the name mounted during its leave transition.
:deep(.logo-title) {
display: none;
}
}
</style> </style>
+14 -11
View File
@@ -4,19 +4,22 @@ import 'virtual:svg-icons-register'
import { createApp } from 'vue' import { createApp } from 'vue'
import { getConfig } from './api/app'
import App from './App.vue' import App from './App.vue'
import install from './install' import install from './install'
import router from './router'
const app = createApp(App) async function start() {
const app = createApp(App)
app.use(install)
// The static boot panel remains in place through auth redirects and lazy route imports.
await router.isReady()
app.mount('#app')
document.getElementById('admin-boot')?.remove()
window.dispatchEvent(new Event('admin:mounted'))
}
app.use(install) start().catch(error => {
app.mount('#app') const panel = document.getElementById('admin-boot')
if (panel) panel.dataset.state = 'error'
getConfig().then((res) => { console.error('管理后台启动失败:', error)
console.log(
`%c likeadmin %c v${res.version} `,
'padding: 4px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #bbb; font-weight: bold;',
'padding: 4px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #4A5DFF; font-weight: bold;'
)
}) })
+3
View File
@@ -11,6 +11,8 @@ import { INDEX_ROUTE, INDEX_ROUTE_NAME } from './router/routes'
import useTabsStore from './stores/modules/multipleTabs' import useTabsStore from './stores/modules/multipleTabs'
import useUserStore from './stores/modules/user' import useUserStore from './stores/modules/user'
import { clearAuthInfo } from './utils/auth' import { clearAuthInfo } from './utils/auth'
import { installNavigationFeedback } from './utils/nav-loading'
import { reportRouteLoad } from './utils/route-load-notice'
import { isExternal } from './utils/validate' import { isExternal } from './utils/validate'
function firstQueryString(q: LocationQueryValue | LocationQueryValue[] | undefined): string { function firstQueryString(q: LocationQueryValue | LocationQueryValue[] | undefined): string {
@@ -82,6 +84,7 @@ const changePasswordPath = '/change-password'
const bindWorkWechatPath = '/bind-work-wechat' const bindWorkWechatPath = '/bind-work-wechat'
// 免登录白名单 // 免登录白名单
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403] const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
installNavigationFeedback(router, document, reportRouteLoad)
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
document.title = to.meta.title ?? config.title document.title = to.meta.title ?? config.title
const userStore = useUserStore() const userStore = useUserStore()
+25 -6
View File
@@ -27,17 +27,34 @@ export function filterAsyncRoutes(routes: any[], firstRoute = true) {
// 创建一条路由记录 // 创建一条路由记录
export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordRaw { export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordRaw {
const normalizedPath = normalizeMenuPath(route.paths) const remote = isExternal(route.paths)
const rawPath = String(route.paths || '')
const queryAt = remote ? -1 : rawPath.indexOf('?')
const normalizedPath = normalizeMenuPath(queryAt < 0 ? rawPath : rawPath.slice(0, queryAt))
let menuParams = route.params
if (queryAt !== -1) {
// Route patterns never contain the URL query. Some menu records store
// it in paths instead of the separate params field. Keep an empty path
// empty: it is a valid index child of the parent (e.g. 自录转化统计).
const inline = Object.fromEntries(new URLSearchParams(rawPath.slice(queryAt + 1)))
let extra: Record<string, unknown> = {}
if (typeof menuParams === 'string' && menuParams) {
if (menuParams.trim().startsWith('{')) {
try { extra = JSON.parse(menuParams) ?? {} } catch { /* ignore malformed menu defaults */ }
} else { extra = Object.fromEntries(new URLSearchParams(menuParams)) }
}
menuParams = JSON.stringify({ ...inline, ...extra })
}
//@ts-ignore //@ts-ignore
const routeRecord: RouteRecordRaw = { const routeRecord: RouteRecordRaw = {
path: isExternal(route.paths) ? route.paths : firstRoute ? `/${normalizedPath}` : normalizedPath, path: remote ? route.paths : firstRoute ? `/${normalizedPath}` : normalizedPath,
name: Symbol(route.paths), name: Symbol(route.paths),
meta: { meta: {
hidden: !route.is_show, hidden: !route.is_show,
keepAlive: !!route.is_cache, keepAlive: !!route.is_cache,
title: route.name, title: route.name,
perms: route.perms, perms: route.perms,
query: route.params, query: menuParams,
icon: route.icon, icon: route.icon,
type: route.type, type: route.type,
activeMenu: route.selected activeMenu: route.selected
@@ -61,9 +78,11 @@ export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordR
export function loadRouteView(component: string) { export function loadRouteView(component: string) {
try { try {
const normalizedComponent = normalizeMenuPath(component) const normalizedComponent = normalizeMenuPath(component)
const key = Object.keys(modules).find((key) => { // Menus store paths relative to views/. A suffix alone can open a different
return key.includes(`/${normalizedComponent}.vue`) // authorized page, e.g. assistant_service/workbench/index instead of workbench/index.
}) const exact = `/src/views/${normalizedComponent}.vue`
if (Object.hasOwn(modules, exact)) return modules[exact]
const key = Object.keys(modules).find(key => key.endsWith(`/${normalizedComponent}.vue`))
if (key) { if (key) {
return modules[key] return modules[key]
} }
+22
View File
@@ -2,6 +2,12 @@ import { defineStore } from 'pinia'
import { getConfig } from '@/api/app' import { getConfig } from '@/api/app'
import configs from '@/config' import configs from '@/config'
import { ScreenEnum } from '@/enums/appEnums'
import cache from '@/utils/cache'
const DESKTOP_COLLAPSE_KEY = 'admin_ui_v2_desktop_collapsed'
const nativeSidebar = !['live-readonly', 'local-preview'].includes(import.meta.env.MODE)
type AdminUi = 'v2' | 'legacy'
interface AppSate { interface AppSate {
config: Record<string, any> config: Record<string, any>
@@ -9,17 +15,20 @@ interface AppSate {
configFetchAttempted: boolean configFetchAttempted: boolean
isMobile: boolean isMobile: boolean
isCollapsed: boolean isCollapsed: boolean
desktopV2Collapsed: boolean | null
isRouteShow: boolean isRouteShow: boolean
} }
const useAppStore = defineStore({ const useAppStore = defineStore({
id: 'app', id: 'app',
state: (): AppSate => { state: (): AppSate => {
const saved = nativeSidebar ? cache.get(DESKTOP_COLLAPSE_KEY) : null
return { return {
config: {}, config: {},
configFetchAttempted: false, configFetchAttempted: false,
isMobile: true, isMobile: true,
isCollapsed: false, isCollapsed: false,
desktopV2Collapsed: typeof saved === 'boolean' ? saved : null,
isRouteShow: true isRouteShow: true
} }
}, },
@@ -59,6 +68,19 @@ const useAppStore = defineStore({
setMobile(value: boolean) { setMobile(value: boolean) {
this.isMobile = value this.isMobile = value
}, },
syncSidebarViewport(width: number, ui: AdminUi) {
this.setMobile(width <= ScreenEnum.SM)
const preferDesktop = nativeSidebar && ui === 'v2' && !this.isMobile
this.isCollapsed = (preferDesktop ? this.desktopV2Collapsed : null) ?? (width < ScreenEnum.MD)
},
toggleHeaderCollapsed(ui: AdminUi) {
this.toggleCollapsed()
// Drawer/route/layout updates are transient; only this button records the desktop choice.
if (nativeSidebar && ui === 'v2' && !this.isMobile) {
this.desktopV2Collapsed = this.isCollapsed
cache.set(DESKTOP_COLLAPSE_KEY, this.isCollapsed)
}
},
toggleCollapsed(toggle?: boolean) { toggleCollapsed(toggle?: boolean) {
this.isCollapsed = toggle ?? !this.isCollapsed this.isCollapsed = toggle ?? !this.isCollapsed
}, },
+21 -76
View File
@@ -13,6 +13,7 @@ import { isExternal } from '@/utils/validate'
interface TabItem { interface TabItem {
name: RouteRecordName name: RouteRecordName
fullPath: string fullPath: string
cacheId?: number
path: string path: string
title?: string title?: string
query?: LocationQuery query?: LocationQuery
@@ -20,9 +21,8 @@ interface TabItem {
} }
interface TabsSate { interface TabsSate {
cacheTabList: Set<string> nextCacheId: number
tabList: TabItem[] tabList: TabItem[]
tasMap: Record<string, TabItem>
indexRouteName: RouteRecordName indexRouteName: RouteRecordName
} }
@@ -33,7 +33,10 @@ const getHasTabIndex = (fullPath: string, tabList: TabItem[]) => {
/** 同一菜单页可能因 query、重定向等产生不同 fullPath,用 name + 解析后的 path 去重 */ /** 同一菜单页可能因 query、重定向等产生不同 fullPath,用 name + 解析后的 path 去重 */
const getTabMergeKey = (item: Pick<TabItem, 'name' | 'path'>) => { const getTabMergeKey = (item: Pick<TabItem, 'name' | 'path'>) => {
if (item.name == null || item.name === '') return '' if (item.name == null || item.name === '') return ''
return `${String(item.name)}::${item.path}` // Router resolves an index child both with and without its parent's final
// slash. Only normalize the tab identity, never the navigation URL.
const path = item.path.replace(/\/+$/, '') || '/'
return `${String(item.name)}::${path}`
} }
const isCannotAddRoute = (route: RouteLocationNormalized, router: Router) => { const isCannotAddRoute = (route: RouteLocationNormalized, router: Router) => {
@@ -47,58 +50,33 @@ const isCannotAddRoute = (route: RouteLocationNormalized, router: Router) => {
return false return false
} }
const findTabsIndex = (fullPath: string, tabList: TabItem[]) => { // fullPath already includes resolved dynamic params, encoded query, and fragment.
return tabList.findIndex((item) => item.fullPath === fullPath) export const getRouteParams = (tabItem: TabItem) => tabItem.fullPath
}
const getComponentName = (route: RouteLocationNormalized) => {
return route.matched.at(-1)?.components?.default?.name
}
export const getRouteParams = (tabItem: TabItem) => {
const { params, path, query } = tabItem
return {
params: params || {},
path,
query: query || {}
}
}
const useTabsStore = defineStore({ const useTabsStore = defineStore({
id: 'tabs', id: 'tabs',
state: (): TabsSate => ({ state: (): TabsSate => ({
cacheTabList: new Set(), nextCacheId: 0,
tabList: [], tabList: [],
tasMap: {},
indexRouteName: '' indexRouteName: ''
}), }),
getters: { getters: {
getTabList(): TabItem[] { getTabList(): TabItem[] {
return this.tabList return this.tabList
},
getCacheTabList(): string[] {
return Array.from(this.cacheTabList)
} }
}, },
actions: { actions: {
setRouteName(name: RouteRecordName) { setRouteName(name: RouteRecordName) {
this.indexRouteName = name this.indexRouteName = name
}, },
addCache(componentName?: string) { refreshCachedTab(fullPath: string) {
if (componentName) this.cacheTabList.add(componentName) const tab = this.tabList.find(item => item.fullPath === fullPath)
}, if (!tab?.cacheId) return false
removeCache(componentName?: string) { tab.cacheId = ++this.nextCacheId
if (componentName && this.cacheTabList.has(componentName)) { return true
this.cacheTabList.delete(componentName)
}
},
clearCache() {
this.cacheTabList.clear()
}, },
resetState() { resetState() {
this.cacheTabList = new Set()
this.tabList = [] this.tabList = []
this.tasMap = {}
this.indexRouteName = '' this.indexRouteName = ''
}, },
addTab(router: Router) { addTab(router: Router) {
@@ -106,23 +84,19 @@ const useTabsStore = defineStore({
const { name, query, meta, params, fullPath, path } = route const { name, query, meta, params, fullPath, path } = route
if (isCannotAddRoute(route, router)) return if (isCannotAddRoute(route, router)) return
const hasTabIndex = getHasTabIndex(fullPath!, this.tabList) const hasTabIndex = getHasTabIndex(fullPath!, this.tabList)
const componentName = getComponentName(route)
const tabItem = { const tabItem = {
name: name!, name: name!,
path, path,
fullPath, fullPath,
cacheId: meta.keepAlive ? (this.tabList[hasTabIndex]?.cacheId ?? ++this.nextCacheId) : undefined,
title: meta?.title, title: meta?.title,
query, query,
params params
} }
if (meta?.keepAlive) {
this.addCache(componentName)
}
// 已存在相同 fullPath:刷新该项(标题/query 等可能变化) // 已存在相同 fullPath:刷新该项(标题/query 等可能变化)
if (hasTabIndex !== -1) { if (hasTabIndex !== -1) {
this.tabList[hasTabIndex] = tabItem this.tabList[hasTabIndex] = tabItem
this.tasMap[fullPath!] = tabItem
return return
} }
@@ -136,54 +110,26 @@ const useTabsStore = defineStore({
const keepIdx = dupIndices[0] const keepIdx = dupIndices[0]
for (let k = dupIndices.length - 1; k >= 1; k--) { for (let k = dupIndices.length - 1; k >= 1; k--) {
const idx = dupIndices[k] const idx = dupIndices[k]
delete this.tasMap[this.tabList[idx].fullPath]
this.tabList.splice(idx, 1) this.tabList.splice(idx, 1)
} }
const prev = this.tabList[keepIdx]
if (prev.fullPath !== fullPath) {
delete this.tasMap[prev.fullPath]
}
this.tabList[keepIdx] = tabItem this.tabList[keepIdx] = tabItem
this.tasMap[fullPath!] = tabItem
return return
} }
} }
this.tasMap[fullPath!] = tabItem
this.tabList.push(tabItem) this.tabList.push(tabItem)
}, },
removeTab(fullPath: string, router: Router) { removeTab(fullPath: string, router: Router) {
const { currentRoute, push } = router const { currentRoute, push } = router
const index = findTabsIndex(fullPath, this.tabList) const index = getHasTabIndex(fullPath, this.tabList)
// 移除tab if (index < 0 || this.tabList.length < 2) return
if (this.tabList.length > 1) { this.tabList.splice(index, 1)
index !== -1 && this.tabList.splice(index, 1) if (fullPath === currentRoute.value.fullPath) {
push(getRouteParams(this.tabList[Math.max(0, index - 1)]))
} }
const componentName = getComponentName(currentRoute.value)
this.removeCache(componentName)
if (fullPath !== currentRoute.value.fullPath) {
return
}
// 删除选中的tab
let toTab: TabItem | null = null
if (index === 0) {
toTab = this.tabList[index]
} else {
toTab = this.tabList[index - 1]
}
const toRoute = getRouteParams(toTab)
push(toRoute)
}, },
removeOtherTab(route: RouteLocationNormalized) { removeOtherTab(route: RouteLocationNormalized) {
this.tabList = this.tabList.filter((item) => item.fullPath == route.fullPath) this.tabList = this.tabList.filter(item => item.fullPath === route.fullPath)
const componentName = getComponentName(route)
this.cacheTabList.forEach((name) => {
if (componentName !== name) {
this.removeCache(name)
}
})
}, },
removeAllTab(router: Router) { removeAllTab(router: Router) {
const { push, currentRoute } = router const { push, currentRoute } = router
@@ -193,7 +139,6 @@ const useTabsStore = defineStore({
return return
} }
this.tabList = [] this.tabList = []
this.clearCache()
push(PageEnum.INDEX) push(PageEnum.INDEX)
} }
} }
+157 -61
View File
@@ -1,90 +1,186 @@
import { isObject } from '@vue/shared' import { isObject } from '@vue/shared'
import { createSharedComposable, useDark, useStorage } from '@vueuse/core'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import defaultSetting, { import defaultSetting, { SETTING_SCHEMA_MIGRATIONS, SETTING_SCHEMA_VERSION } from '@/config/setting'
SETTING_SCHEMA_MIGRATIONS,
SETTING_SCHEMA_VERSION
} from '@/config/setting'
import { SETTING_KEY } from '@/enums/cacheEnums' import { SETTING_KEY } from '@/enums/cacheEnums'
import cache from '@/utils/cache' import cache from '@/utils/cache'
import { setTheme } from '@/utils/theme' import { setTheme } from '@/utils/theme'
const storageSetting = cache.get(SETTING_KEY) type AdminUi = 'legacy' | 'v2'
type ColorMode = 'auto' | 'dark' | 'light'
function applySettingSchemaMigrations( const APPEARANCE_KEY = 'admin_ui'
state: Record<string, any>, const ART_SETTING_KEY = 'admin_ui_v2_setting'
storedVersion: number // Art Design Pro f3aaf58: config/index.ts and config/setting.ts.
) { export const artMainColors = ['#5D87FF', '#B48DF3', '#1D84FF', '#60C041', '#38C0FC', '#F9901F', '#FF80C8']
if (storedVersion >= SETTING_SCHEMA_VERSION) return const artDefaults = {
for (let ver = storedVersion + 1; ver <= SETTING_SCHEMA_VERSION; ver++) { ...defaultSetting,
const keys = SETTING_SCHEMA_MIGRATIONS[ver] theme: artMainColors[0],
if (!keys) continue sideTheme: 'design',
for (const key of keys) { sideDarkColor: '#191A23',
state[key] = defaultSetting[key] sideWidth: 230,
showLogo: true,
successTheme: '#13deb9',
warningTheme: '#ffae1f',
dangerTheme: '#ff4d4f',
errorTheme: '#fa896b',
colorMode: 'auto' as ColorMode
}
function initialAppearance() {
const root = document.documentElement
const preview = root.dataset.adminUi === 'v2'
const stored = cache.get(APPEARANCE_KEY)
const mode: AdminUi = preview || stored === 'v2' || (stored !== 'legacy' && root.dataset.defaultAdminUi === 'v2') ? 'v2' : 'legacy'
root.dataset.adminUi = mode
return { preview, mode }
}
export const useAdminAppearanceStore = defineStore('adminAppearance', {
state: initialAppearance,
actions: {
select(mode: AdminUi) {
this.mode = mode
document.documentElement.dataset.adminUi = mode
if (!this.preview) cache.set(APPEARANCE_KEY, mode)
} }
} }
state._settingSchemaVersion = SETTING_SCHEMA_VERSION })
const { showDrawer, ...persist } = state
cache.set(SETTING_KEY, persist) function loadLegacy(preview: boolean): Record<string, any> {
const stored = cache.get(SETTING_KEY)
const state: Record<string, any> = { ...defaultSetting, ...stored }
if (isObject(stored)) {
const version = Number(stored._settingSchemaVersion) || 0
for (let i = version + 1; i <= SETTING_SCHEMA_VERSION; i++) {
for (const key of SETTING_SCHEMA_MIGRATIONS[i] || []) state[key] = defaultSetting[key]
}
if (!preview && version < SETTING_SCHEMA_VERSION) {
cache.set(SETTING_KEY, { ...state, _settingSchemaVersion: SETTING_SCHEMA_VERSION })
}
}
return { ...state, _settingSchemaVersion: SETTING_SCHEMA_VERSION }
}
function isHex(value: unknown): value is string {
return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value)
}
function loadArt(legacy: Record<string, any>) {
const stored = cache.get(ART_SETTING_KEY)
// Only inherit an actual, non-default accent. The old dark menu / 183px width
// are classic preferences, not a selected Art menu style or sidebar size.
const inherited = isHex(legacy.theme) && legacy.theme.toLowerCase() !== defaultSetting.theme.toLowerCase()
? legacy.theme : artDefaults.theme
return { ...artDefaults, theme: inherited, ...(isObject(stored) ? stored : {}) }
}
function persistProfile(mode: AdminUi, state: Record<string, any>) {
// Only profile settings enter localStorage, never the drawer or the other profile.
const defaults = mode === 'v2' ? artDefaults : defaultSetting
const settings = Object.fromEntries(Object.keys(defaults).map(key => [key, state[key]]))
if (mode === 'legacy') settings._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.set(mode === 'v2' ? ART_SETTING_KEY : SETTING_KEY, settings)
}
// Upstream utils/ui/colors.ts floors each RGB channel. CSS color-mix and the
// classic theme helper round differently (notably light-9 and the dark ramp).
function artPalette(primary: string, isDark: boolean) {
const rgb = [1, 3, 5].map(i => parseInt(primary.slice(i, i + 2), 16))
const colorAt = (level: number, dark: boolean) => '#' + rgb.map(channel =>
Math.floor(dark ? channel * (1 - level) : (255 - channel) * level + channel)
.toString(16).padStart(2, '0')
).join('')
const vars: Record<string, string> = { '--el-color-primary': primary, '--el-color-primary-rgb': rgb.join(', ') }
for (let i = 1; i <= 9; i++) {
vars[`--el-color-primary-light-${i}`] = colorAt(i / 10, isDark)
vars[`--el-color-primary-dark-${i}`] = colorAt(i / 10, true)
}
// Preserve the upstream white on blue; avoid white-on-white for a custom near-white accent.
const luma = rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722
vars['--zyt-on-primary'] = luma > 200 ? '#29343D' : '#fff'
vars['--zyt-selected-ink'] = !isDark && luma > 220 ? '#29343D' : primary
return vars
} }
export const useSettingStore = defineStore({ export const useSettingStore = defineStore({
id: 'setting', id: 'setting',
state: () => { state: () => {
const state: Record<string, any> = { const appearance = useAdminAppearanceStore()
showDrawer: false, const legacy = loadLegacy(appearance.preview)
...defaultSetting const profiles: Record<AdminUi, Record<string, any>> = { legacy, v2: loadArt(legacy) }
return {
profiles, showDrawer: false, ...defaultSetting, colorMode: 'auto' as ColorMode,
...profiles[appearance.mode]
} }
let storedVersion = SETTING_SCHEMA_VERSION },
if (isObject(storageSetting)) { getters: {
storedVersion = adminUi(): AdminUi { return useAdminAppearanceStore().mode }
typeof (storageSetting as any)._settingSchemaVersion === 'number'
? (storageSetting as any)._settingSchemaVersion
: 0
Object.assign(state, storageSetting)
if (storedVersion < SETTING_SCHEMA_VERSION) {
applySettingSchemaMigrations(state, storedVersion)
}
}
state._settingSchemaVersion = SETTING_SCHEMA_VERSION
return state
}, },
actions: { actions: {
// 设置布局设置 toggleAdminUi() {
setSetting(data: Record<string, any>) { const keys = Object.keys(this.adminUi === 'v2' ? artDefaults : defaultSetting) as (keyof typeof artDefaults)[]
const { key, value } = data this.profiles[this.adminUi] = Object.fromEntries(keys.map(key => [key, this.$state[key]]))
if (this.hasOwnProperty(key)) { const mode = this.adminUi === 'v2' ? 'legacy' : 'v2'
//@ts-ignore this.$patch(this.profiles[mode])
this[key] = value useAdminAppearanceStore().select(mode)
},
setSetting({ key, value }: { key: string; value: any }) {
if (!(key in this.$state) || key === 'profiles') return
this.$patch({ [key]: value })
if (key !== 'showDrawer' && !useAdminAppearanceStore().preview) {
persistProfile(this.adminUi, this.$state)
} }
const settings: any = Object.assign({}, this.$state)
delete settings.showDrawer
settings._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.set(SETTING_KEY, settings)
}, },
// 设置主题色
setTheme(isDark: boolean) { setTheme(isDark: boolean) {
setTheme( if (this.adminUi === 'v2') {
{ const vars = artPalette(isHex(this.theme) ? this.theme : artDefaults.theme, isDark)
primary: this.theme, // Separate, scoped sheet so leaving v2 instantly restores classic including poppers.
success: this.successTheme, let style = document.getElementById('art-theme-vars')
warning: this.warningTheme, if (!style) {
danger: this.dangerTheme, style = document.createElement('style')
error: this.errorTheme, style.id = 'art-theme-vars'
info: this.infoTheme document.head.appendChild(style)
}, }
isDark style.textContent = "html:root[data-admin-ui='v2']{" +
) Object.entries(vars).map(([k,v]) => k + ':' + v).join(';') + '}'
} else {
setTheme({
primary: this.theme, success: this.successTheme, warning: this.warningTheme,
danger: this.dangerTheme, error: this.errorTheme, info: this.infoTheme
}, isDark)
}
}, },
resetTheme() { resetTheme() {
for (const key in defaultSetting) { if (this.adminUi === 'v2') {
//@ts-ignore this.$patch({ ...artDefaults })
this[key] = defaultSetting[key] if (!useAdminAppearanceStore().preview) persistProfile('v2', artDefaults)
} else {
this.$patch({ ...defaultSetting })
if (!useAdminAppearanceStore().preview) cache.remove(SETTING_KEY)
} }
this._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.remove(SETTING_KEY)
} }
} }
}) })
// A single system-dark listener / palette writer shared by the root and drawer.
// The old vueuse-color-scheme key remains the owner of the classic preference.
export const useAdminDark = createSharedComposable(() => {
const settings = useSettingStore()
const normalMode = useStorage<ColorMode>('vueuse-color-scheme', 'auto', undefined, { writeDefaults: false })
const classicMode = useAdminAppearanceStore().preview ? ref(normalMode.value) : normalMode
const storageRef = computed<ColorMode>({
get: () => settings.adminUi === 'v2' ? settings.colorMode : classicMode.value,
set(value) {
if (settings.adminUi === 'v2') settings.setSetting({ key: 'colorMode', value })
else classicMode.value = value
}
})
const dark = useDark({ storageRef })
watch([dark, () => settings.adminUi, () => settings.theme], () => settings.setTheme(dark.value), { immediate: true })
return dark
})
export default useSettingStore export default useSettingStore
+100
View File
@@ -0,0 +1,100 @@
// SidebarSubmenu.vue / theme.scss (Art Design Pro f3aaf58): inline and flyout
// rows share the label/icon geometry, but not the indent or selection style.
:root[data-admin-ui='v2'] {
:is(.side .admin-nav-tree, .admin-nav-popper.el-menu--popup-container) {
--nav-arrow-width: 13px;
--nav-arrow-gap: 8px;
--nav-row-end: var(--el-menu-base-level-padding);
.admin-nav-link { display: block; }
.el-sub-menu[tabindex='0']:focus-visible > .el-sub-menu__title,
.admin-nav-link[id]:focus-visible > .el-menu-item {
outline: 2px solid var(--zyt-nav-selected);
outline-offset: -2px;
}
.menu-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu-item-icon {
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
width: 20px;
height: 20px;
margin-right: 8px;
&.admin-nav-icon--empty { width: 0; }
}
.el-sub-menu > .el-sub-menu__title {
padding-right: calc(var(--nav-row-end) + var(--nav-arrow-width) + var(--nav-arrow-gap));
// Element's width: inherit otherwise copies the *row* width onto
// this absolutely positioned icon. Leave its native rotation intact.
> .el-sub-menu__icon-arrow {
position: absolute;
right: var(--nav-row-end);
top: 50%;
width: var(--nav-arrow-width);
height: var(--nav-arrow-width);
margin: calc(var(--nav-arrow-width) / -2) 0 0;
font-size: var(--nav-arrow-width);
pointer-events: none;
}
}
}
.side .menu.admin-nav-tree {
// Element supplies --el-menu-level at each actual submenu; text-only
// rows keep Art's empty icon wrapper margin, not an invented glyph.
.el-menu--vertical:not(.el-menu--collapse) {
--el-menu-base-level-padding: 20px;
--el-menu-level-padding: 20px;
}
.el-menu--collapse {
> .el-sub-menu > .el-sub-menu__title,
> .admin-nav-link > .el-menu-item > .el-menu-tooltip__trigger {
padding: 0;
justify-content: center;
> .menu-item-icon { margin: 0; }
// Keep even a custom top-level route without an icon identifiable.
> .admin-nav-icon--empty {
width: 20px;
font: 500 14px/1 var(--el-font-family);
&::before { content: attr(data-initial); }
}
}
}
}
// The first flyout lives under body; deeper flyouts may live in that popper.
// Space the direct entries, not the li inside each router-link.
.admin-nav-popper.el-menu--popup-container > .el-menu--popup {
width: max-content;
min-width: min(200px, calc(100vw - 32px));
max-width: min(320px, calc(100vw - 32px));
padding: 8px;
background: var(--zyt-nav-bg);
> :not(:last-child) { margin-bottom: 5px; }
.el-menu-item, .el-sub-menu__title {
height: 40px;
line-height: 40px;
margin: 0;
border: 0;
border-radius: 6px;
color: var(--zyt-nav-text);
}
.menu-item-icon { margin: 0 5px 0 0; color: var(--zyt-nav-icon); }
.el-menu-item:hover, .el-sub-menu__title:hover, .el-menu-item.is-active {
color: var(--art-gray-900);
background: var(--art-gray-200);
}
}
&.dark .admin-nav-popper.el-menu--popup-container > .el-menu--popup .el-menu-item.is-active {
background: #292a2e;
}
}
+291
View File
@@ -0,0 +1,291 @@
// Scope the Art profile at the root, including Element poppers teleported to body.
// Reference: Art Design Pro f3aaf58, assets/styles/core/{tailwind,app,el-*}.
@use 'sass:color';
@mixin art-status-colors($mix-target, $pressed-target) {
@each $name, $base in (success: #13deb9, warning: #ffae1f, danger: #ff4d4f, error: #fa896b, info: #909399) {
--el-color-#{$name}: #{$base};
--el-color-#{$name}-rgb: #{color.channel($base, "red", $space: rgb)}, #{color.channel($base, "green", $space: rgb)}, #{color.channel($base, "blue", $space: rgb)};
@each $step in 3, 5, 7, 8, 9 {
--el-color-#{$name}-light-#{$step}: #{color.mix($mix-target, $base, $step * 10%)};
}
--el-color-#{$name}-dark-2: #{color.mix($pressed-target, $base, 20%)};
}
}
:root[data-admin-ui='v2'] {
--art-gray-100: #f9fafb;
--art-gray-200: #f2f4f5;
--art-gray-300: #e6eaeb;
--art-gray-400: #dbdfe1;
--art-gray-500: #949eb7;
--art-gray-600: #7987a1;
--art-gray-700: #4d5875;
--art-gray-800: #383853;
--art-gray-900: #323251;
--zyt-canvas: #fafbfc;
--zyt-surface: #fff;
--zyt-surface-subtle: var(--art-gray-100);
--zyt-card-border: rgba(0, 0, 0, .08);
--zyt-border: #e2e8ee;
--zyt-hover: #edeff0;
--zyt-ink: var(--art-gray-900);
--zyt-text: var(--art-gray-700);
--zyt-muted: var(--art-gray-600);
--zyt-radius: .75rem;
--zyt-shadow: none; // Art's default boxBorderMode.
--zyt-primary: var(--el-color-primary);
--zyt-accent: var(--el-color-primary);
// Keep status indicators legible even with a near-white/black custom accent.
--zyt-feedback-ink: var(--zyt-text);
--zyt-loading-surface: var(--zyt-surface);
--zyt-accent-soft: var(--el-color-primary-light-9);
--zyt-accent-border: var(--el-color-primary-light-8);
--zyt-nav-bg: #fff;
--zyt-nav-title: var(--art-gray-800);
--zyt-nav-icon: #6b6b6b;
--zyt-nav-text: #29343d;
--zyt-nav-hover: var(--art-gray-200);
--zyt-nav-active: var(--el-color-primary-light-9);
--zyt-nav-selected: var(--zyt-selected-ink, var(--el-color-primary));
--zyt-nav-arrow: var(--art-gray-600);
// Runtime default/picker shades come from upstream's integer RGB algorithm.
--el-color-primary: #5d87ff;
--el-color-primary-light-9: #eef3ff;
--el-font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-family: var(--el-font-family);
--el-font-weight-primary: 400;
--el-bg-color: var(--zyt-surface);
--el-bg-color-page: var(--zyt-canvas);
--el-bg-color-overlay: var(--zyt-surface);
--el-fill-color-blank: var(--zyt-surface);
--el-fill-color-light: var(--zyt-surface-subtle);
--el-text-color-primary: var(--zyt-ink);
--el-text-color-regular: var(--zyt-text);
--el-text-color-secondary: var(--zyt-muted);
--el-component-size: 36px;
--el-border-radius-base: calc(var(--zyt-radius) / 3 + 2px);
--el-border-radius-small: calc(var(--zyt-radius) / 3 + 4px);
--el-menu-item-height: 42px;
--el-menu-sub-item-height: 42px;
--el-menu-icon-width: 20px;
--el-menu-base-level-padding: 20px;
--el-menu-level-padding: 20px;
--navbar-height: 60px;
--table-header-bg-color: var(--zyt-surface-subtle);
@include art-status-colors(#fff, #000);
@supports (color: color-mix(in srgb, black, white)) {
--zyt-feedback-ink: color-mix(in srgb, var(--zyt-primary) 30%, var(--zyt-ink));
--zyt-loading-surface: color-mix(in srgb, var(--zyt-surface) 90%, transparent);
}
.side--dark, &.dark {
--zyt-nav-bg: #191a23;
--zyt-nav-title: #d9dadb;
--zyt-nav-icon: #babbbd;
--zyt-nav-text: #babbbd;
--zyt-nav-hover: #0f1015;
--zyt-nav-active: #27282d;
--zyt-nav-selected: #fff;
--zyt-nav-arrow: var(--art-gray-400);
}
&.dark {
--art-gray-100: #110f0f;
--art-gray-200: #17171c;
--art-gray-300: #393946;
--art-gray-400: #505062;
--art-gray-500: #73738c;
--art-gray-600: #8f8fa3;
--art-gray-700: #ababba;
--art-gray-800: #c7c7d1;
--art-gray-900: #e3e3e8;
--zyt-canvas: #070707;
--zyt-surface: #161618;
--zyt-surface-subtle: var(--art-gray-200);
--zyt-card-border: rgba(255, 255, 255, .08);
--zyt-border: rgba(255, 255, 255, .1);
--zyt-hover: #252530;
--el-text-color-regular: rgba(255, 255, 255, .85);
@include art-status-colors(#141414, #fff);
// In system dark all three styles use darkMenuStyles, not a white panel.
&, .side--dark {
--zyt-nav-bg: var(--zyt-surface);
--zyt-nav-title: #ddd;
--zyt-nav-icon: var(--art-gray-800);
--zyt-nav-text: var(--art-gray-800);
--zyt-nav-selected: var(--zyt-selected-ink, var(--el-color-primary));
--zyt-nav-arrow: #fff;
}
}
.main-wrap, .layout-default, .app-header, .navbar, .app-header .app-tabs {
background-color: var(--zyt-canvas);
}
.app-header { position: relative; z-index: 2; }
.navbar { padding-inline: 20px; }
.navbar .navbar-item {
color: var(--art-gray-700);
border-radius: var(--el-border-radius-base);
&:hover { background: var(--zyt-hover); }
}
.app-header .app-tabs {
padding: 0 20px 12px;
border: 0;
.el-tabs { height: 32px; --el-tabs-header-height: 32px; }
.el-tabs__item {
height: 32px;
margin-right: 6px;
border: 1px solid var(--zyt-card-border);
border-radius: calc(var(--zyt-radius) / 2.5 + 2px);
background: var(--zyt-surface);
color: var(--zyt-muted);
font-size: 12px;
&.is-active, &:hover { color: var(--zyt-primary); }
&.is-active::before, &.is-active::after { display: none; }
}
}
.admin-content { padding: 0 20px 20px; }
.navbar:last-child { margin-bottom: 12px; }
.side {
background: var(--zyt-nav-bg);
border-right-color: var(--zyt-card-border);
}
.logo, .admin-nav-heading {
flex: none;
display: flex;
align-items: center;
gap: 10px;
height: var(--navbar-height);
padding-inline: 22px;
color: var(--zyt-nav-title);
white-space: nowrap;
font-size: 18px;
.logo-title { position: static; font-size: inherit; color: inherit; }
svg { color: var(--zyt-primary); }
}
.side .menu .el-menu {
--el-menu-bg-color: var(--zyt-nav-bg);
--el-menu-text-color: var(--zyt-nav-text);
--el-menu-active-color: var(--zyt-nav-selected);
--el-menu-hover-bg-color: var(--zyt-nav-hover);
}
.side .menu {
.el-menu-item, .el-sub-menu__title {
height: 42px;
line-height: 42px;
width: calc(100% - 16px);
margin: 0 8px 4px;
border-radius: 6px;
font-size: 14px;
color: var(--zyt-nav-text);
transition: background-color 0s;
}
.menu-item-icon { margin-left: -7px; color: var(--zyt-nav-icon); font-size: 20px !important; }
.el-sub-menu__icon-arrow { color: var(--zyt-nav-arrow); font-size: 13px; }
.el-sub-menu__title:hover, .el-menu-item:not(.is-active):hover {
background: var(--zyt-nav-hover);
color: var(--zyt-nav-text);
}
.el-menu .el-menu-item.is-active {
border: 0;
background: var(--zyt-nav-active);
color: var(--zyt-nav-selected);
font-weight: 400;
.menu-item-icon { color: inherit; }
}
.el-menu--collapse { width: 64px; }
.el-menu--collapse .is-active > .el-sub-menu__title .menu-item-icon { color: var(--zyt-primary); }
}
// The LIGHT theme alone has the full-width item and 4px stripe. DESIGN is flat.
&:not(.dark) .side--light .menu {
.el-menu-item, .el-sub-menu__title { width: 100%; margin-inline: 0; border-radius: 0; }
.menu-item-icon { margin-left: 1px; }
.el-menu-item.is-active::before {
position: absolute;
inset: 0 auto 0 0;
width: 4px;
content: '';
background: var(--zyt-primary);
}
}
.el-menu--popup-container .el-menu--popup {
padding: 8px; background: var(--zyt-surface);
.el-menu-item, .el-sub-menu__title {
height: 40px; margin-bottom: 5px; border: 0; border-radius: 6px; color: var(--zyt-text);
&:hover, &.is-active { background: var(--art-gray-200); color: var(--art-gray-900); }
}
}
&.dark .el-menu--popup-container .el-menu--popup .el-menu-item.is-active { background: #292a2e; }
.art-menu-options {
display: flex; gap: 6px; margin-top: 12px;
button {
padding: 5px 12px;
background: var(--zyt-surface);
border: 1px solid var(--zyt-border);
border-radius: 6px;
color: var(--zyt-text);
&[aria-pressed='true'] { border-color: var(--zyt-primary); color: var(--zyt-primary); background: var(--zyt-accent-soft); }
}
}
.el-card {
--el-card-border-radius: calc(var(--zyt-radius) + 4px);
--el-card-border-color: var(--zyt-card-border);
--el-card-bg-color: var(--zyt-surface);
box-shadow: none;
}
.el-table { font-variant-numeric: tabular-nums; }
.el-overlay-dialog .el-dialog { border-radius: calc(var(--zyt-radius) / 1.2 + 2px); }
.el-message-box, .el-popover { border-radius: var(--el-border-radius-small); }
.el-dialog__title { font-size: 16px; }
// Our locked Element Plus ships a literal 32px base height. Map default-size
// buttons to the upstream 36px, without enlarging compact or text actions.
.el-button:not(.el-button--small, .el-button--large, .is-link, .is-text) {
height: var(--el-component-size);
&.is-circle { width: var(--el-component-size); }
}
.el-button--primary:not(.is-plain, .is-text, .is-link, .is-disabled) {
--el-button-text-color: var(--zyt-on-primary, #fff);
--el-button-active-text-color: var(--zyt-on-primary, #fff);
--el-button-hover-text-color: var(--zyt-on-primary, #fff);
}
.el-pagination.is-background :is(.btn-next, .btn-prev, .el-pager li) { border-radius: 6px; }
// Ring the visible control, not the small or hidden input inside it.
// An outline leaves Element's error border and checked state intact.
:is(button, a[href], summary, [role='button'], [role='tab'], [role='menuitem'], [role='option']):focus-visible,
.el-textarea__inner:focus-visible,
:is(.el-input__wrapper, .el-select__wrapper, .el-checkbox__input, .el-radio__input, .el-switch):has(input:focus-visible) {
outline: 2px solid var(--zyt-feedback-ink);
outline-offset: var(--zyt-focus-offset, 2px);
}
.side, .app-tabs { --zyt-focus-offset: -2px; }
.side--dark { --zyt-feedback-ink: var(--zyt-nav-title); }
// Match the surface beneath local table/panel loads, without changing a
// full-screen lock, the original request lifecycle, or an explicit mask color.
.el-loading-mask:not(.is-fullscreen) {
--el-mask-color: var(--zyt-loading-surface);
--el-loading-spinner-size: 28px;
border-radius: inherit;
.el-loading-spinner {
display: grid;
justify-items: center;
gap: 5px;
margin-top: 0;
transform: translateY(-50%);
.path { stroke: var(--zyt-feedback-ink); stroke-width: 3.5; }
.el-loading-text { margin: 0; color: var(--zyt-text); }
}
}
// Keep the native busy icon and button label visible without the extra veil.
.el-button.is-loading { --el-mask-color-extra-light: transparent; }
@media (prefers-reduced-motion: reduce) {
.el-loading-mask, .el-button, .el-select__wrapper { transition-duration: 0s; }
.el-loading-spinner .circular, .el-loading-spinner .path,
.el-button.is-loading .el-icon.is-loading { animation: none; }
}
@media (max-width: 640px) {
.admin-content { padding-inline: 15px; }
.navbar, .app-header .app-tabs { padding-inline: 15px; }
}
}
+2
View File
@@ -3,3 +3,5 @@
@import 'var.css'; @import 'var.css';
@import 'tailwind.css'; @import 'tailwind.css';
@import 'public.scss'; @import 'public.scss';
@import 'admin-v2.scss';
@import 'admin-nav-tree.scss';
+52
View File
@@ -0,0 +1,52 @@
import { isNavigationFailure, NavigationFailureType, type RouteLocationNormalized, type Router } from 'vue-router'
/**
* Observe the navigation, never decide it. Keep one lightweight bar across redirects
* and overlapping guards; a late failure for an older route doesn't own the bar.
*/
export function installNavigationFeedback(router: Router, doc: Document = document,
notify?: (failedPath?: string) => void) {
let owner: RouteLocationNormalized | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let bar: HTMLElement | undefined
function stop() {
clearTimeout(timer)
timer = undefined
owner = undefined
bar?.remove()
bar = undefined
}
function owns(to: RouteLocationNormalized) {
return owner === to || (to.redirectedFrom && to.redirectedFrom === (owner?.redirectedFrom ?? owner))
}
router.beforeEach(to => {
if (doc.getElementById('admin-boot')) return
notify?.()
owner = to
if (timer !== undefined || bar) return
timer = setTimeout(() => {
timer = undefined
bar = doc.createElement('div')
bar.id = 'admin-route-progress'
bar.setAttribute('role', 'progressbar')
bar.setAttribute('aria-label', '正在打开页面')
doc.body.appendChild(bar)
}, 180)
})
router.afterEach((to, _from, failure) => {
// Duplicates bypass beforeEach, including redirects back to the current route.
if (owns(to) || isNavigationFailure(failure, NavigationFailureType.duplicated)) stop()
})
router.onError((error, to) => {
if (owns(to)) {
stop()
// Page assets failed after the app started. Don't reload over an
// unsaved form or mistake a background request for a route error.
notify?.(to.fullPath)
}
console.error('路由导航失败:', error)
})
}
+5
View File
@@ -0,0 +1,5 @@
import { shallowRef } from 'vue'
// Ephemeral UI state. Navigation targets are issued only by the existing router.
export const failedRoute = shallowRef<string>()
export function reportRouteLoad(path?: string) { failedRoute.value = path }
+16 -1
View File
@@ -7,7 +7,12 @@
根据安全策略,需绑定企业微信账号后方可使用管理后台 根据安全策略,需绑定企业微信账号后方可使用管理后台
</div> </div>
<div v-if="wxWorkAutoAuth" class="text-center py-10"> <div v-if="liveNative" class="text-center">
<a class="el-button el-button--primary" href="https://admin.zhenyangtang.com.cn/admin/bind-work-wechat" target="_blank" rel="noopener noreferrer">在正式后台绑定企业微信 ↗</a>
<p class="mt-3 text-sm">绑定完成后返回这里刷新,系统会重新核对账号状态。</p>
<el-button class="mt-3" @click="recheckBinding">重新核对绑定状态</el-button>
</div>
<div v-else-if="wxWorkAutoAuth" class="text-center py-10">
<el-icon class="is-loading mb-4" :size="40" color="var(--el-color-primary)"> <el-icon class="is-loading mb-4" :size="40" color="var(--el-color-primary)">
<Loading /> <Loading />
</el-icon> </el-icon>
@@ -78,6 +83,15 @@ function getOAuthQuery(): URLSearchParams {
return merged return merged
} }
const liveNative = import.meta.env.MODE === 'live-native'
async function recheckBinding() {
try {
await userStore.getUserInfo()
const flag = userStore.userInfo.need_bind_work_wechat
if ([false,0,'0'].includes(flag)) await router.replace(userStore.isPaw === 0 ? '/change-password' : '/')
else ElMessage.info('正式后台尚未确认绑定,请先完成企业微信绑定。')
} catch { ElMessage.info('请重新登录以核对绑定状态。') }
}
const handleLogout = () => { const handleLogout = () => {
userStore.logout() userStore.logout()
} }
@@ -140,6 +154,7 @@ const renderQr = async () => {
} }
onMounted(async () => { onMounted(async () => {
if (liveNative) return // 绑定回调仅由已经登记的正式域名处理。
// 与 axios 拦截器竞态:首屏若有请求先返回 10,可能在 onMounted 执行前就 router.replace 清掉 query;同步快照尽量早读 // 与 axios 拦截器竞态:首屏若有请求先返回 10,可能在 onMounted 执行前就 router.replace 清掉 query;同步快照尽量早读
let oauthCodeSnapshot = '' let oauthCodeSnapshot = ''
try { try {
+29 -9
View File
@@ -81,7 +81,11 @@
<!-- 企业微信扫码登录(非企业微信内浏览器) --> <!-- 企业微信扫码登录(非企业微信内浏览器) -->
<template v-if="loginMode === 'wxwork'"> <template v-if="loginMode === 'wxwork'">
<div class="wxwork-qrcode-wrap"> <div v-if="liveNative" class="wxwork-native-entry">
<a class="el-button el-button--primary" :href="officialQrHref" target="_blank" rel="noopener noreferrer" referrerpolicy="no-referrer">企业微信扫码登录 ↗</a>
<p>二维码在企业微信页面打开;扫码后进入正式后台。</p>
</div>
<div v-else class="wxwork-qrcode-wrap">
<div v-if="wxWorkLoading" class="text-center py-10"> <div v-if="wxWorkLoading" class="text-center py-10">
<el-icon class="is-loading" :size="32" color="var(--el-color-primary)"> <el-icon class="is-loading" :size="32" color="var(--el-color-primary)">
<Loading /> <Loading />
@@ -90,7 +94,7 @@
</div> </div>
<div v-else id="wxwork_qrcode_container" class="wxwork-qrcode"></div> <div v-else id="wxwork_qrcode_container" class="wxwork-qrcode"></div>
</div> </div>
<div class="text-center text-sm text-gray-400 mt-4"> <div v-if="!liveNative" class="text-center text-sm text-gray-400 mt-4">
请使用企业微信扫描二维码登录 请使用企业微信扫描二维码登录
</div> </div>
</template> </template>
@@ -106,7 +110,7 @@
<icon name="el-icon-ArrowRight" size="16" /> <icon name="el-icon-ArrowRight" size="16" />
</span> </span>
</el-button> </el-button>
<p class="iam-login-hint">使用统一身份平台账号登录</p> <p class="iam-login-hint">{{ liveNative ? '使用统一身份平台账号登录正式后台' : '使用统一身份平台账号登录' }}</p>
</section> </section>
</template> </template>
</div> </div>
@@ -131,6 +135,8 @@ import useUserStore from '@/stores/modules/user'
import cache from '@/utils/cache' import cache from '@/utils/cache'
import { getIamConfig, getWorkWechatConfig } from '@/api/user' import { getIamConfig, getWorkWechatConfig } from '@/api/user'
const liveNative = import.meta.env.MODE === 'live-native'
const officialLogin = 'https://admin.zhenyangtang.com.cn/admin/login'
const passwordRef = shallowRef<InputInstance>() const passwordRef = shallowRef<InputInstance>()
const formRef = shallowRef<FormInstance>() const formRef = shallowRef<FormInstance>()
const appStore = useAppStore() const appStore = useAppStore()
@@ -160,7 +166,7 @@ const loadIamConfig = async () => {
try { try {
const result = await getIamConfig() const result = await getIamConfig()
const url = new URL(result?.loginUrl || '', window.location.origin) const url = new URL(result?.loginUrl || '', window.location.origin)
if (result?.enabled === true && url.protocol === 'https:') { if (result?.enabled === true && url.protocol === 'https:' && (!liveNative || (url.origin === new URL(officialLogin).origin && url.pathname === '/adminapi/iam/start'))) {
iamLoginUrl.value = url.href iamLoginUrl.value = url.href
iamEnabled.value = true iamEnabled.value = true
} }
@@ -171,7 +177,8 @@ const loadIamConfig = async () => {
const handleIamLogin = () => { const handleIamLogin = () => {
if (iamEnabled.value && iamLoginUrl.value) { if (iamEnabled.value && iamLoginUrl.value) {
window.location.assign(iamLoginUrl.value) if (liveNative) window.open(iamLoginUrl.value, '_blank', 'noopener,noreferrer')
else window.location.assign(iamLoginUrl.value)
} }
} }
@@ -220,9 +227,20 @@ const wxWorkLoading = ref(false)
const isInWxWork = () => /wxwork/i.test(navigator.userAgent) const isInWxWork = () => /wxwork/i.test(navigator.userAgent)
const getRedirectUri = () => { const getRedirectUri = () => {
if (liveNative) return officialLogin
return window.location.origin + window.location.pathname return window.location.origin + window.location.pathname
} }
// This origin is not a registered enterprise OAuth callback. A top-level
// provider flow keeps codes/tickets at the original authorized production page.
const officialQrHref = computed(() => {
const {corp_id, agent_id} = wxWorkConfig.value
if (!corp_id || !agent_id) return officialLogin
const url = new URL('https://open.work.weixin.qq.com/wwopen/sso/qrConnect')
url.search = new URLSearchParams({appid: corp_id, agentid: String(agent_id), redirect_uri: officialLogin, state: 'admin_login', lang: 'zh'}).toString()
return url.href
})
const handleEnter = () => { const handleEnter = () => {
if (!formData.password) { if (!formData.password) {
return passwordRef.value?.focus() return passwordRef.value?.focus()
@@ -324,7 +342,7 @@ const renderWxWorkQRCode = async () => {
// 切换到企业微信扫码时自动渲染 // 切换到企业微信扫码时自动渲染
watch(loginMode, (val) => { watch(loginMode, (val) => {
if (val === 'wxwork') { if (val === 'wxwork' && !liveNative) {
nextTick(() => renderWxWorkQRCode()) nextTick(() => renderWxWorkQRCode())
} }
}) })
@@ -350,11 +368,11 @@ onMounted(async () => {
// 检查 URL 中是否有企业微信回调 code // 检查 URL 中是否有企业微信回调 code
const urlParams = new URLSearchParams(window.location.search) const urlParams = new URLSearchParams(window.location.search)
void loadIamConfig() void loadIamConfig()
const hasIamCallback = urlParams.has('iam_ticket') || urlParams.has('iam_error') const hasIamCallback = !liveNative && (urlParams.has('iam_ticket') || urlParams.has('iam_error'))
if (hasIamCallback) { if (hasIamCallback) {
await handleIamCallback(urlParams.get('iam_ticket'), urlParams.get('iam_error')) await handleIamCallback(urlParams.get('iam_ticket'), urlParams.get('iam_error'))
} }
const wxCode = hasIamCallback ? null : urlParams.get('code') const wxCode = hasIamCallback || liveNative ? null : urlParams.get('code')
const wxState = urlParams.get('state') const wxState = urlParams.get('state')
if (wxCode && wxState === 'admin_login') { if (wxCode && wxState === 'admin_login') {
@@ -374,7 +392,7 @@ onMounted(async () => {
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id } wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
// 在企业微信内:自动跳转 OAuth 授权 // 在企业微信内:自动跳转 OAuth 授权
if (isInWxWork() && !hasIamCallback && !switchingAccount.value) { if (!liveNative && isInWxWork() && !hasIamCallback && !switchingAccount.value) {
const redirectUri = encodeURIComponent(getRedirectUri()) const redirectUri = encodeURIComponent(getRedirectUri())
const authUrl = const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize` + `https://open.weixin.qq.com/connect/oauth2/authorize` +
@@ -482,6 +500,8 @@ onMounted(async () => {
} }
} }
.wxwork-native-entry { min-height: 145px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; }
.wxwork-native-entry p { color: var(--el-text-color-secondary); font-size: 13px; }
.wxwork-qrcode-wrap { .wxwork-qrcode-wrap {
display: flex; display: flex;
justify-content: center; justify-content: center;

Some files were not shown because too many files have changed in this diff Show More