feat(admin): 恢复原生登录与业务路由并移除预览顶栏

This commit is contained in:
2026-12-01 18:06:31 +08:00
parent 9fe3bd9bb2
commit 6ca42f5312
17 changed files with 400 additions and 46 deletions
+19
View File
@@ -0,0 +1,19 @@
# 本机完整后台(正式 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 --chrome <Chromium路径> --out <本地截图目录>`。测试拦截所有非本机请求,仅用虚构登录/统计数据检查真实组件;不验证真实用户凭据或线上写入。
+234
View File
@@ -0,0 +1,234 @@
"""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")):
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 open_group(parent, name):
label = parent.locator(".el-sub-menu__title").filter(has_text=re.compile("^" + re.escape(name) + "$"))
expect(label).to_be_visible()
group = label.locator("..")
if "is-opened" not in (group.get_attribute("class") or "").split():
label.click()
return group
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)
aside = page.locator(".app-aside .menu:visible")
def entry(name):
parent = open_group(open_group(aside, "数据统计"), "自录数据统计")
return parent.get_by_role("menuitem", name=name, exact=True)
# First visit the sibling; the empty child below must be selected by click, not just by initial redirect.
entry("账户消耗录入").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
entry("自录转化统计").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("--chrome", required=True)
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(executable_path=args.chrome, 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))
+12
View File
@@ -0,0 +1,12 @@
// 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)
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:path.join(root,'node_modules/.zyt-live-native/dist'),emptyOutDir:true,sourcemap:false,reportCompressedSize:false,
rollupOptions:{input:path.join(here,'index.html')}}})
+2
View File
@@ -0,0 +1,2 @@
<!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:,"></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
+29
View File
@@ -0,0 +1,29 @@
// 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 dist=fileURLToPath(new URL('../node_modules/.zyt-live-native/dist/',import.meta.url)), 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`))
+2
View File
@@ -1,3 +1,5 @@
> 历史模式,已由 [本机完整后台](../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 请求,使用服务器原账号权限。只支持本站原生账号密码;扫码/统一登录、首次改密、强制绑定等在正式站点完成。未授权的页面保持关闭。
+1 -1
View File
@@ -1,6 +1,6 @@
# 甄养堂管理后台:合成数据演示(5180)
需要查询真实业务数据?请打开 **[正式数据只读登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [只读服务说明](../live-readonly/README.md),旧入口不会退回到演示版。
需要查询真实业务数据?请打开 **[正式账号登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [完整后台说明](../live-native/README.md),旧入口不会退回到演示版。
## 单独打开演示版
@@ -23,6 +23,7 @@
</div>
<div class="flex items-center">
<button
v-if="!liveNative"
class="admin-ui-toggle"
type="button"
data-admin-ui-toggle
@@ -80,6 +81,7 @@ import MultipleTabs from './multiple-tabs.vue'
import Refresh from './refresh.vue'
import UserDropDown from './user-drop-down.vue'
const liveNative = import.meta.env.MODE === 'live-native'
const appStore = useAppStore()
const isMobile = computed(() => appStore.isMobile)
const isCollapsed = computed(() => appStore.isCollapsed)
@@ -8,6 +8,13 @@
title="主题设置"
>
<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">
<span class="text-tx-secondary">风格设置</span>
<div v-if="settingStore.adminUi === 'v2'" class="art-menu-options" role="group" aria-label="菜单风格">
@@ -102,7 +109,14 @@ import theme_dark from '@/assets/images/theme_black.png'
import theme_light from '@/assets/images/theme_white.png'
import useSettingStore, { artMainColors, useAdminDark } from '@/stores/modules/setting'
const liveNative = import.meta.env.MODE === 'live-native'
const settingStore = useSettingStore()
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 = [
@@ -1,6 +1,6 @@
<template>
<template v-if="!route.meta?.hidden">
<app-link v-if="!hasShowChild" :to="`${routePath}?${queryStr}`">
<app-link v-if="!hasShowChild" :to="menuTarget">
<el-menu-item :index="routePath">
<icon
class="menu-item-icon"
@@ -78,6 +78,10 @@ const queryStr = computed<string>(() => {
return query
}
})
const menuTarget = computed(() => {
const q = String(queryStr.value || '').replace(/^\?/, '')
return q ? `${props.routePath}${props.routePath.includes('?') ? '&' : '?'}${q}` : props.routePath
})
</script>
<style lang="scss" scoped>
.el-menu-item,
-9
View File
@@ -4,7 +4,6 @@ import 'virtual:svg-icons-register'
import { createApp } from 'vue'
import { getConfig } from './api/app'
import App from './App.vue'
import install from './install'
@@ -12,11 +11,3 @@ const app = createApp(App)
app.use(install)
app.mount('#app')
getConfig().then((res) => {
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;'
)
})
+20 -3
View File
@@ -27,17 +27,34 @@ export function filterAsyncRoutes(routes: any[], firstRoute = true) {
// 创建一条路由记录
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
const routeRecord: RouteRecordRaw = {
path: isExternal(route.paths) ? route.paths : firstRoute ? `/${normalizedPath}` : normalizedPath,
path: remote ? route.paths : firstRoute ? `/${normalizedPath}` : normalizedPath,
name: Symbol(route.paths),
meta: {
hidden: !route.is_show,
keepAlive: !!route.is_cache,
title: route.name,
perms: route.perms,
query: route.params,
query: menuParams,
icon: route.icon,
type: route.type,
activeMenu: route.selected
+2 -1
View File
@@ -32,7 +32,8 @@ const artDefaults = {
function initialAppearance() {
const root = document.documentElement
const preview = root.dataset.adminUi === 'v2'
const mode: AdminUi = preview || cache.get(APPEARANCE_KEY) === 'v2' ? 'v2' : 'legacy'
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 }
}
+16 -1
View File
@@ -7,7 +7,12 @@
根据安全策略,需绑定企业微信账号后方可使用管理后台
</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)">
<Loading />
</el-icon>
@@ -78,6 +83,15 @@ function getOAuthQuery(): URLSearchParams {
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 = () => {
userStore.logout()
}
@@ -140,6 +154,7 @@ const renderQr = async () => {
}
onMounted(async () => {
if (liveNative) return // 绑定回调仅由已经登记的正式域名处理。
// 与 axios 拦截器竞态:首屏若有请求先返回 10,可能在 onMounted 执行前就 router.replace 清掉 query;同步快照尽量早读
let oauthCodeSnapshot = ''
try {
+33 -30
View File
@@ -3,8 +3,7 @@
<div class="flex-1 flex items-center justify-center">
<div class="login-card flex rounded-md overflow-hidden">
<div class="flex-1 h-full hidden md:inline-block">
<div v-if="liveReadonly" class="live-login-note"><strong>正式数据 · 只读预览</strong><p>这是本机运行的甄养堂管理后台。账号密码由浏览器直接通过 HTTPS 提交到正式后台,本机服务只提供页面文件。</p><code>admin.zhenyangtang.com.cn</code><p>仅支持已开通的账号密码登录。企业微信、统一登录、首次改密和账号绑定请在正式站点完成。</p><a href="https://admin.zhenyangtang.com.cn/admin/" target="_blank" rel="noopener noreferrer">打开正式后台 ↗</a></div>
<image-contain v-else :src="config.login_image" :width="400" height="100%" />
<image-contain :src="config.login_image" :width="400" height="100%" />
</div>
<div
class="login-form bg-body flex flex-col justify-center px-10 py-10 md:w-[420px] w-[380px] flex-none mx-auto"
@@ -30,7 +29,6 @@
<!-- 账号密码登录 -->
<template v-if="loginMode === 'account'">
<p v-if="liveReadonly" class="live-login-destination">正式账号登录 · 仅查询<br><span>密码直发 admin.zhenyangtang.com.cn,不经本机代理。</span></p>
<el-form ref="formRef" :model="formData" size="large" :rules="rules">
<el-form-item prop="account">
<el-input
@@ -65,7 +63,7 @@
v-model="formData.password"
show-password
placeholder="请输入密码"
@keyup.enter="liveReadonly ? lockLogin() : handleLogin()"
@keyup.enter="handleLogin"
>
<template #prepend>
<icon name="el-icon-Lock" size="16" />
@@ -73,7 +71,7 @@
</el-input>
</el-form-item>
</el-form>
<div v-if="!liveReadonly" class="mb-5">
<div class="mb-5">
<el-checkbox v-model="remAccount" label="记住账号"></el-checkbox>
</div>
<el-button type="primary" size="large" :loading="isLock" @click="lockLogin">
@@ -83,7 +81,11 @@
<!-- 企业微信扫码登录(非企业微信内浏览器) -->
<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">
<el-icon class="is-loading" :size="32" color="var(--el-color-primary)">
<Loading />
@@ -92,7 +94,7 @@
</div>
<div v-else id="wxwork_qrcode_container" class="wxwork-qrcode"></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>
</template>
@@ -108,7 +110,7 @@
<icon name="el-icon-ArrowRight" size="16" />
</span>
</el-button>
<p class="iam-login-hint">使用统一身份平台账号登录</p>
<p class="iam-login-hint">{{ liveNative ? '使用统一身份平台账号登录正式后台' : '使用统一身份平台账号登录' }}</p>
</section>
</template>
</div>
@@ -133,7 +135,8 @@ import useUserStore from '@/stores/modules/user'
import cache from '@/utils/cache'
import { getIamConfig, getWorkWechatConfig } from '@/api/user'
const liveReadonly = import.meta.env.MODE === 'live-readonly'
const liveNative = import.meta.env.MODE === 'live-native'
const officialLogin = 'https://admin.zhenyangtang.com.cn/admin/login'
const passwordRef = shallowRef<InputInstance>()
const formRef = shallowRef<FormInstance>()
const appStore = useAppStore()
@@ -163,7 +166,7 @@ const loadIamConfig = async () => {
try {
const result = await getIamConfig()
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
iamEnabled.value = true
}
@@ -174,7 +177,8 @@ const loadIamConfig = async () => {
const handleIamLogin = () => {
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)
}
}
@@ -223,27 +227,29 @@ const wxWorkLoading = ref(false)
const isInWxWork = () => /wxwork/i.test(navigator.userAgent)
const getRedirectUri = () => {
if (liveNative) return officialLogin
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 = () => {
if (!formData.password) {
return passwordRef.value?.focus()
}
if (liveReadonly) void lockLogin()
else handleLogin()
handleLogin()
}
const handleLogin = async () => {
await formRef.value?.validate()
if (liveReadonly) {
try {
await userStore.login({account: formData.account.trim(), password: formData.password})
await router.replace('/')
} catch (e) { ElMessage.error(e instanceof Error ? e.message : '登录未完成') }
finally { formData.password = '' }
return
}
const result: any = await userStore.login(formData)
const account = formData.account.trim()
const others = rememberedAccounts.value.filter((saved) => saved !== account)
@@ -336,7 +342,7 @@ const renderWxWorkQRCode = async () => {
// 切换到企业微信扫码时自动渲染
watch(loginMode, (val) => {
if (val === 'wxwork') {
if (val === 'wxwork' && !liveNative) {
nextTick(() => renderWxWorkQRCode())
}
})
@@ -349,7 +355,6 @@ function selectRememberedAccount(account: string) {
}
onMounted(async () => {
if (liveReadonly) return
// 恢复记住账号
const value = cache.get(ACCOUNT_KEY)
const saved: unknown[] = Array.isArray(value?.accounts) ? value.accounts : value?.remember ? [value.account] : []
@@ -363,11 +368,11 @@ onMounted(async () => {
// 检查 URL 中是否有企业微信回调 code
const urlParams = new URLSearchParams(window.location.search)
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) {
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')
if (wxCode && wxState === 'admin_login') {
@@ -387,7 +392,7 @@ onMounted(async () => {
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
// 在企业微信内:自动跳转 OAuth 授权
if (isInWxWork() && !hasIamCallback && !switchingAccount.value) {
if (!liveNative && isInWxWork() && !hasIamCallback && !switchingAccount.value) {
const redirectUri = encodeURIComponent(getRedirectUri())
const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize` +
@@ -495,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 {
display: flex;
justify-content: center;
@@ -514,7 +521,3 @@ onMounted(async () => {
}
}
</style>
<style scoped>
.live-login-note{width:330px;min-height:100%;padding:44px 32px;display:flex;flex-direction:column;justify-content:center;gap:17px;background:var(--el-color-primary-light-9);color:var(--el-text-color-regular);font-size:14px;line-height:1.75}.live-login-note strong{font-size:22px;color:var(--el-text-color-primary)}.live-login-note code,.live-login-note a{color:var(--el-color-primary)}.live-login-destination{font-size:14px;margin:0 0 18px}.live-login-destination span{font-size:12px;color:var(--el-text-color-secondary)}
</style>
+5
View File
@@ -189,6 +189,10 @@ const getBindRedirectUri = () => {
// 打开绑定弹窗,渲染扫码
const showBindDialog = async () => {
if (import.meta.env.MODE === 'live-native') {
window.open('https://admin.zhenyangtang.com.cn/admin/user/setting', '_blank', 'noopener,noreferrer')
return
}
bindDialogVisible.value = true
bindLoading.value = true
@@ -276,6 +280,7 @@ onMounted(async () => {
}
// 检查是否是绑定回调
if (import.meta.env.MODE === 'live-native') return // 本机不接收正式企微绑定回调。
const urlParams = new URLSearchParams(window.location.search)
const bindCode = urlParams.get('code')
const state = urlParams.get('state')
@@ -66,3 +66,7 @@
## 第二批:可核对的多模块数据
用户列表/详情、医生周排班和部门预约统计已适配 Art 主题;本地专用预约明细把三者与原订单模块串起来。部门统计按挂号医助的部门而非患者或收款人的部门汇总。用户账号关联患者档案,订单数表示该患者的订单数,不冒充该次预约的收费。排班按时间段和号源核对占用量,取消预约不占号。生产业务写权限未向预览开放。详见[预览导航与快照说明](../../admin/local-preview/README.md)。
## 本机正式账号入口切换为原生后台
5179 现运行 [live-native](../../admin/live-native/README.md) 构建。此前的只读菜单投影和测试顶栏不再作为入口;真实菜单直接加载现有业务组件,权限和业务写操作由正式服务决定。自录转化统计是目录下的空路径默认子页。恢复原登录布局、线上品牌图和配置启用的企微/IAM 选项;这两种方式仍使用正式域受信回调,本机账号密码登录使用正式 API。未将这次前端改动发布到线上。