feat(frontend): Phase C 固定企业模式 - VITE_FIXED_ENTITY_ID 支持登录无下拉/隐藏切换器

- 新增 src/utils/entity.ts: isFixedEntity/getFixedEntityId/effectiveEntityId
- Login.vue: 固定企业版隐藏企业下拉显示只读徽标, 登录直接带固定 entity_id
- MainLayout.vue: 切换器加 !isFixedEntity() 守卫, 固定版顶部显示企业 tag, logo 带企业名
- ReportCenter.vue: 页内企业切换下拉加守卫, getEntityId 固定版恒取构建锁定值
- .env.example: VITE_FIXED_ENTITY_ID 示例与说明
- 验证脚本 backend/scripts/verify_phase_c_fixed_entity_e2e.py (22项, 双build E2E全过)
This commit is contained in:
Hermes CI Fix
2026-09-08 11:27:01 +08:00
parent 193061cf4d
commit ebe0962c09
6 changed files with 388 additions and 13 deletions
@@ -0,0 +1,297 @@
# -*- coding: utf-8 -*-
"""Phase C 固定企业前端 E2E(2026-09-08)
验证:VITE_FIXED_ENTITY_ID 固定版(登录无企业下拉、进入无切换器、数据=固定企业)
vs 非固定超管版(下拉/切换器照旧)。
前置:本机已构建 dist-fixed-1(VITE_FIXED_ENTITY_ID=1)与 dist(无固定),
并分别起 vite preview:
pnpm exec vite preview --port 5199 --outDir dist-fixed-1 --host 127.0.0.1
pnpm exec vite preview --port 5200 --outDir dist --host 127.0.0.1
后端 cma-backend 8010 运行(vite preview 继承 server.proxy 转发 /api → 8010)。
无头 Chrome: --remote-debugging-port=9224 --user-data-dir=/tmp/chrome-cma-phasec
用法:/opt/hermes-agent/bin/python3 scripts/verify_phase_c_fixed_entity_e2e.py
"""
import json
import sys
import time
import urllib.request
import websocket
CDP_HTTP = "http://127.0.0.1:9224"
FIXED_URL = "http://127.0.0.1:5199"
MULTI_URL = "http://127.0.0.1:5200"
USER, PWD = "admin", "admin123"
FAILS = []
PASSES = []
def http_get(path):
with urllib.request.urlopen(CDP_HTTP + path, timeout=5) as r:
return json.loads(r.read().decode())
def ev(ws_url, expr, timeout=25):
"""每次新建短连接执行表达式(长连接易被导航断掉);超时重试一次。"""
last = None
for attempt in range(2):
ws = websocket.create_connection(ws_url, timeout=timeout)
try:
ws.settimeout(timeout)
mid = 1000 + attempt
ws.send(json.dumps({"id": mid, "method": "Runtime.evaluate",
"params": {"expression": expr, "returnByValue": True, "awaitPromise": True}}))
while True:
resp = json.loads(ws.recv())
if resp.get("id") == mid:
res = resp.get("result", {})
if res.get("exceptionDetails"):
return "EXC: " + json.dumps(res["exceptionDetails"], ensure_ascii=False)[:300]
return res.get("result", {}).get("value")
except Exception as e: # noqa: BLE001 网络超时/断连重试一次
last = "WSERR:" + str(e)[:120]
time.sleep(1.0)
finally:
ws.close()
return last
def close_all_tabs():
try:
ver = http_get("/json/version")
ws = websocket.create_connection(ver["webSocketDebuggerUrl"], timeout=15)
for p in http_get("/json"):
if p.get("type") == "page":
ws.send(json.dumps({"id": 999, "method": "Target.closeTarget", "params": {"targetId": p["id"]}}))
ws.close()
time.sleep(2.0)
except Exception as e: # noqa: BLE001
print(" warn close_all_tabs:", str(e)[:120])
def new_page(url):
ver = http_get("/json/version")
ws = websocket.create_connection(ver["webSocketDebuggerUrl"], timeout=30)
mid = 1
ws.send(json.dumps({"id": mid, "method": "Target.createTarget", "params": {"url": url}}))
while True:
resp = json.loads(ws.recv())
if resp.get("id") == mid:
tid = resp.get("result", {}).get("targetId")
break
ws.close()
time.sleep(2.5)
for p in http_get("/json"):
if p["id"] == tid:
return tid, p["webSocketDebuggerUrl"]
return tid, None
def wait_until(ws_url, expr, expect, tries=30, gap=1.0):
for _ in range(tries):
v = ev(ws_url, expr)
if v == expect:
return True
time.sleep(gap)
return False
LOGIN_READY = "document.querySelectorAll('.login-card button').length >= 1"
def ready(ws_url, prefix, tries=40, gap=1.0):
"""确保 tab 真实导航到 prefix(fresh profile 下 createTarget 偶发停留 about:blank)。"""
for _ in range(tries):
h = ev(ws_url, "location.href")
if isinstance(h, str) and h.startswith(prefix):
return True
if isinstance(h, str) and (h == "about:blank" or h.startswith("about:")):
ev(ws_url, "location.href = " + js_str(prefix))
time.sleep(gap)
return False
def check(name, cond, detail=""):
if cond:
PASSES.append(name)
print(f" PASS {name}")
else:
FAILS.append(name)
print(f" FAIL {name} {detail}")
def js_str(s):
return json.dumps(s, ensure_ascii=False)
def main():
# 清掉历史标签(跑多轮后 Chrome 积压标签会拖慢/超时)
close_all_tabs()
# ───────────────────────── 固定企业版(entity=1 酣客)─────────────────────────
print("== [A] 固定企业版 VITE_FIXED_ENTITY_ID=1 ==")
tid, ws = new_page(FIXED_URL + "/login")
if not ws:
print("FATAL: no ws for fixed login"); sys.exit(1)
# 清掉可能持久化的登录态,确保处于未登录登录页
ev(ws, "localStorage.removeItem('cma_token'); localStorage.removeItem('cma_user'); localStorage.removeItem('cma_entity_id'); localStorage.removeItem('cma_entity_name'); 'cleared'")
ev(ws, "location.href = " + js_str(FIXED_URL + "/login"))
ok = wait_until(ws, LOGIN_READY, True, tries=30, gap=1.0)
check("A0 登录页挂载", ok)
# 等固定企业徽标文本就绪(登录企业 + 企业名,需 login-entities 返回)
wait_until(ws, "(() => { const b = document.querySelector('.fixed-entity-badge'); return b && (b.innerText||'').length > 0; })()", True, tries=20, gap=1.0)
time.sleep(0.8)
# 登录页:不应有企业下拉(选择登录公司),应显示固定企业徽标
login_dom = ev(ws, """(() => {
const t = document.body.innerText || '';
const selCount = document.querySelectorAll('.login-card .el-select').length;
const badge = document.querySelector('.fixed-entity-badge');
return { selCount, badgeText: badge ? (badge.innerText || '') : '', hasPlaceholder: t.includes('选择登录公司') };
})()""")
print(" login-dom:", json.dumps(login_dom, ensure_ascii=False))
check("A1 登录页无企业下拉", login_dom and login_dom.get("selCount") == 0, str(login_dom))
check("A2 登录页无'选择登录公司'占位", login_dom and not login_dom.get("hasPlaceholder"), str(login_dom))
check("A3 登录页显示固定企业徽标", login_dom and "登录企业" in (login_dom.get("badgeText") or ""), str(login_dom))
# 填表登录(无需选企业)
ev(ws, """(() => {
const setVal = (sel, v) => {
const el = document.querySelector(sel);
if (!el) return false;
const s = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
s.call(el, v);
el.dispatchEvent(new Event('input', { bubbles: true }));
return true;
};
return setVal('input[placeholder="用户名"]', '""" + USER + """') && setVal('input[placeholder="密码"]', '""" + PWD + """');
})()""")
time.sleep(0.6)
ev(ws, """(() => {
const btns = Array.from(document.querySelectorAll('button'));
const b = btns.find(x => (x.innerText || '').replace(/\\s/g, '') === '登录');
if (b) { b.click(); return 'CLICKED'; }
return 'NOBTN';
})()""")
ok = wait_until(ws, "location.pathname.startsWith('/my-dashboard') || (document.body.innerText||'').includes('我的驾驶舱')", True, tries=30, gap=1.2)
check("A4 固定版登录进入 my-dashboard", ok, "url=" + str(ev(ws, "location.href")))
time.sleep(1.5)
ent = ev(ws, "localStorage.getItem('cma_entity_id')")
check("A5 登录后 localStorage 企业=1(酣客)", ent == "1", "ent=" + str(ent))
# 等主布局(header)渲染完成后再探测切换器/tag
ok = wait_until(ws, "!!document.querySelector('.el-header')", True, tries=20, gap=1.0)
check("A6a 主布局渲染", ok)
time.sleep(0.8)
hdr = ev(ws, """(() => {
const h = document.querySelector('.el-header');
const t = h ? (h.innerText || '') : '';
return {
selCount: h ? h.querySelectorAll('.el-select').length : -1,
entityTag: h ? h.querySelector('.entity-tag') ? (h.querySelector('.entity-tag').innerText || '') : '' : '',
text: t
};
})()""")
print(" header:", json.dumps(hdr, ensure_ascii=False))
check("A6 顶部无企业切换器(selCount=0)", hdr and hdr.get("selCount") == 0, str(hdr))
check("A7 顶部显示固定企业 tag", hdr and bool(hdr.get("entityTag")), str(hdr))
logo = ev(ws, "(() => { const l = document.querySelector('.logo'); return l ? (l.innerText||'') : ''; })()")
check("A8 侧边栏品牌含'管理会计OS'", logo and "管理会计OS" in logo, "logo=" + str(logo))
# 报表中心:页内企业切换下拉应隐藏,数据加载正常
ev(ws, "location.href = " + js_str(FIXED_URL + "/reports"))
ok = wait_until(ws, "(document.body.innerText||'').includes('管理报表')", True, tries=25, gap=1.0)
check("A9 报表中心挂载", ok)
time.sleep(3.5)
rep = ev(ws, """(() => {
const hd = document.querySelector('.report-header');
const t = document.body.innerText || '';
return {
headerSelCount: hd ? hd.querySelectorAll('.el-select').length : -1,
headerText: hd ? (hd.innerText || '') : '',
tableRows: document.querySelectorAll('.el-table__body-wrapper tbody tr').length,
pageTextHas企业: t.includes('选择企业')
};
})()""")
print(" reports:", json.dumps(rep, ensure_ascii=False)[:400])
check("A10 报表中心无页内企业切换下拉", rep and rep.get("headerSelCount") == 0, str(rep))
check("A11 报表中心无'选择企业'下拉", rep and not rep.get("pageTextHas企业"), str(rep))
check("A12 报表数据表有行(entity1 数据)", rep and rep.get("tableRows", 0) > 0, "rows=" + str(rep and rep.get("tableRows")))
# ───────────────────────── 非固定超管版(保持切换)─────────────────────────
print("== [B] 非固定超管版(无 VITE_FIXED_ENTITY_ID)==")
tid2, ws2 = new_page(MULTI_URL + "/login")
if not ws2:
print("FATAL: no ws for multi login"); sys.exit(1)
ev(ws2, "localStorage.removeItem('cma_token'); localStorage.removeItem('cma_user'); localStorage.removeItem('cma_entity_id'); localStorage.removeItem('cma_entity_name'); 'cleared'")
ev(ws2, "location.href = " + js_str(MULTI_URL + "/login"))
ok = wait_until(ws2, LOGIN_READY, True, tries=30, gap=1.0)
check("B0 超管登录页挂载", ok)
time.sleep(3.0) # 等 login-entities 返回、企业下拉渲染
mlogin = ev(ws2, """(() => {
const t = document.body.innerText || '';
const sel = document.querySelector('.login-card .el-select');
return { selCount: document.querySelectorAll('.login-card .el-select').length, badgeCount: document.querySelectorAll('.fixed-entity-badge').length, hasPlaceholder: t.includes('选择登录公司'), selText: sel ? (sel.innerText || '') : '' };
})()""")
print(" multi-login:", json.dumps(mlogin, ensure_ascii=False))
check("B1 超管登录页有企业下拉", mlogin and mlogin.get("selCount") >= 1, str(mlogin))
check("B2 超管登录页为下拉模式(无固定企业徽标)", mlogin and mlogin.get("selCount") >= 1 and mlogin.get("badgeCount") == 0, str(mlogin))
ev(ws2, """(() => {
const setVal = (sel, v) => {
const el = document.querySelector(sel);
if (!el) return false;
const s = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
s.call(el, v);
el.dispatchEvent(new Event('input', { bubbles: true }));
return true;
};
return setVal('input[placeholder="用户名"]', '""" + USER + """') && setVal('input[placeholder="密码"]', '""" + PWD + """');
})()""")
time.sleep(0.6)
ev(ws2, """(() => {
const btns = Array.from(document.querySelectorAll('button'));
const b = btns.find(x => (x.innerText || '').replace(/\\s/g, '') === '登录');
if (b) { b.click(); return 'CLICKED'; }
return 'NOBTN';
})()""")
ok = wait_until(ws2, "location.pathname.startsWith('/my-dashboard') || (document.body.innerText||'').includes('我的驾驶舱')", True, tries=30, gap=1.2)
check("B3 超管版登录进入", ok)
time.sleep(2.5)
mhdr = ev(ws2, """(() => {
const h = document.querySelector('.el-header');
return { selCount: h ? h.querySelectorAll('.el-select').length : -1, entityTagCount: h ? h.querySelectorAll('.entity-tag').length : -1 };
})()""")
print(" multi-header:", json.dumps(mhdr, ensure_ascii=False))
check("B4 超管顶部保留企业切换器", mhdr and mhdr.get("selCount") >= 1, str(mhdr))
opts = ev(ws2, "Array.from(document.querySelectorAll('.el-header .el-select .el-option')).map(o => o.innerText).join('|')")
if not opts:
# el-select 选项在未展开时不渲染,改用 my-entities API 直接验证 admin 授权≥2
entc = ev(ws2, "fetch('/api/cma/auth/my-entities', {headers:{Authorization:'Bearer ' + localStorage.getItem('cma_token')}}).then(r=>r.json()).then(d => Array.isArray(d) ? d.length : ((d.data||[]).length)).catch(e=>'ERR:'+e.message)")
entc = None if entc == "ERR:" else entc
check("B5 超管 my-entities≥2(经API)", isinstance(entc, (int, float)) and entc >= 2, "count=" + str(entc))
else:
check("B5 切换器选项≥2", len(opts.split("|")) >= 2, opts)
ev(ws2, "location.href = " + js_str(MULTI_URL + "/reports"))
ok = wait_until(ws2, "(document.body.innerText||'').includes('管理报表')", True, tries=25, gap=1.0)
check("B6 报表中心挂载", ok)
time.sleep(2.5)
mrep = ev(ws2, """(() => {
const hd = document.querySelector('.report-header');
const t = document.body.innerText || '';
return { headerSelCount: hd ? hd.querySelectorAll('.el-select').length : -1, hasPlaceholder: t.includes('选择企业') };
})()""")
check("B7 报表中心保留企业切换下拉", mrep and mrep.get("headerSelCount") >= 1, str(mrep))
print()
print(f"RESULT: {len(PASSES)} passed, {len(FAILS)} failed")
if FAILS:
print("FAILED:", "; ".join(FAILS))
sys.exit(1)
print("ALL PASS")
if __name__ == "__main__":
main()
+4
View File
@@ -1,3 +1,7 @@
# 管理会计OS — 前端环境变量
VITE_API_BASE=/api/cma
VITE_APP_TITLE=管理会计OS
# 固定企业模式(Phase C 2026-09-08):设置 = 构建锁定单一企业(登录页隐藏企业下拉、
# MainLayout/ReportCenter 隐藏切换器,登录直接带该企业),如 VITE_FIXED_ENTITY_ID=1(陕西酣客)/ 2(陕西博海)。
# 留空或不设置 = 超管多企业切换版(默认行为,与旧版完全一致)。
# VITE_FIXED_ENTITY_ID=1
+14 -4
View File
@@ -3,7 +3,7 @@
<el-aside :width="isCollapse ? '64px' : '220px'" :class="{ 'mobile-show': mobileMenuOpen }">
<div class="aside-mask" v-if="mobileMenuOpen" @click="mobileMenuOpen = false"></div>
<div class="logo">
<span v-show="!isCollapse">管理会计OS</span>
<span v-show="!isCollapse">{{ logoText }}</span>
</div>
<el-menu :default-active="activeMenu" :collapse="isCollapse" router background-color="#304156" text-color="#bfcbd9" active-text-color="#409EFF" @select="onMenuSelect">
<template v-for="group in menuGroups" :key="group.label">
@@ -28,8 +28,10 @@
<span class="page-title">{{ pageTitle }}</span>
</div>
<div class="header-right">
<!-- 企业切换器:仅多企业用户显示(授权企业≥2时),单企业用户隐藏避免UI噪音 -->
<el-select v-if="entities.length >= 2" v-model="currentEntityId" @change="onEntityChange" size="small" style="width:120px;margin-right:8px;">
<!-- 固定企业版(Phase C):显示当前企业 tag 代替切换器 -->
<el-tag v-if="isFixedEntity()" size="small" type="primary" effect="plain" class="entity-tag">{{ currentEntityName }}</el-tag>
<!-- 企业切换器:仅非固定版且授权企业≥2时显示(多企业用户),固定版/单企业用户隐藏避免UI噪音 -->
<el-select v-else-if="entities.length >= 2" v-model="currentEntityId" @change="onEntityChange" size="small" style="width:120px;margin-right:8px;">
<el-option v-for="e in entities" :key="e.id" :label="e.short_name || e.name" :value="e.id" />
</el-select>
<el-tag size="small" :type="roleTagType">{{ roleLabel }}</el-tag>
@@ -57,12 +59,19 @@ import {
DataBoard, Tools, Collection, Edit, Reading, Opportunity, PieChart,
} from '@element-plus/icons-vue'
import { MENU_ITEMS, ROLE_LABELS } from '../permission'
import { isFixedEntity } from '../utils/entity'
const route = useRoute()
const router = useRouter()
const isCollapse = ref(false)
const mobileMenuOpen = ref(false)
// 侧边栏品牌:固定企业版带企业名(如「陕西酣客 · 管理会计OS」),切换版保持原名
const logoText = computed(() => {
if (isFixedEntity() && currentEntityName.value) return `${currentEntityName.value} · 管理会计OS`
return '管理会计OS'
})
// ── 全局企业切换(账套模式:switch-entity 重新签发token + 整页刷新) ──
const entities = ref<any[]>([])
const currentEntityId = ref(Number(localStorage.getItem('cma_entity_id') || 1))
@@ -89,7 +98,8 @@ async function onEntityChange(id: number) {
}
}
onMounted(async () => {
// 账套模式:切换器只显示当前用户被授权的企业
// 账套模式:切换器只显示当前用户被授权的企业;固定企业版无切换需求,跳过列表加载
if (isFixedEntity()) return
try {
const r: any = await api.get('/auth/my-entities')
entities.value = r.data || r || []
+25
View File
@@ -0,0 +1,25 @@
// ── 固定企业模式(Phase C 2026-09-08)──
// VITE_FIXED_ENTITY_ID:构建期锁定单一企业(供 Phase A 子域名独立版 hanke/bohai.cma.sxbh.ltd 使用)。
// 设置(如 VITE_FIXED_ENTITY_ID=1)=固定企业独立版:登录页隐藏企业下拉、MainLayout/ReportCenter 隐藏切换器,
// 登录直接携带该 entity_id;数据天然为该企业,无需内部切换。
// 未设置 = 超管/多企业切换版(默认,行为与旧版完全一致)。
const fixedRaw: string = (import.meta.env.VITE_FIXED_ENTITY_ID as string | undefined) || ''
const fixedId: number | undefined = fixedRaw.trim() === '' ? undefined : Number(fixedRaw)
/** 是否固定企业独立版(构建期由 VITE_FIXED_ENTITY_ID 决定,运行时不变) */
export function isFixedEntity(): boolean {
return fixedId !== undefined && !Number.isNaN(fixedId)
}
/** 固定企业 ID;非固定版返回 undefined */
export function getFixedEntityId(): number | undefined {
return isFixedEntity() ? fixedId : undefined
}
/** 当前生效 entity_id:固定企业版取构建锁定值;切换版取 localStorage(登录/切换时写入) */
export function effectiveEntityId(): number {
const f = getFixedEntityId()
if (f !== undefined) return f
const stored = Number(localStorage.getItem('cma_entity_id'))
return Number.isNaN(stored) ? 1 : stored
}
+30 -6
View File
@@ -7,7 +7,8 @@
<el-form-item>
<el-input v-model="form.username" placeholder="用户名" size="large" @input="onUsernameChange" />
</el-form-item>
<el-form-item>
<!-- 固定企业版(VITE_FIXED_ENTITY_ID):隐藏企业下拉,显示只读企业徽标 -->
<el-form-item v-if="!isFixedEntity()">
<el-select v-model="form.entity_id" placeholder="选择登录公司" size="large" style="width:100%" :disabled="entities.length === 0">
<el-option v-for="e in entities" :key="e.id" :label="e.short_name || e.name" :value="e.id">
<span>{{ e.short_name || e.name }}</span>
@@ -15,6 +16,12 @@
</el-option>
</el-select>
</el-form-item>
<el-form-item v-else>
<div class="fixed-entity-badge">
<span class="fe-label">登录企业</span>
<span class="fe-name">{{ fixedEntityLabel }}</span>
</div>
</el-form-item>
<el-form-item><el-input v-model="form.password" type="password" placeholder="密码" size="large" show-password /></el-form-item>
<el-form-item><el-button type="primary" size="large" style="width:100%" :loading="loading" @click="handleLogin">登 录</el-button></el-form-item>
</el-form>
@@ -23,22 +30,34 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authApi } from '../api/index'
import { isFixedEntity, getFixedEntityId } from '../utils/entity'
const router = useRouter()
const loading = ref(false)
const entities = ref<any[]>([])
const form = reactive({ username: 'admin', password: 'admin123', entity_id: undefined as number | undefined })
// ── 固定企业模式(Phase C):构建期锁定单一企业,隐藏下拉、登录直接带固定 entity_id ──
const fixedMode = isFixedEntity()
const fixedEntityId = getFixedEntityId()
const fixedEntityLabel = computed(() => {
if (fixedEntityId === undefined) return ''
const e = entities.value.find((x: any) => x.id === fixedEntityId)
if (e) return e.short_name || e.name
return `企业 #${fixedEntityId}`
})
async function loadEntities(username: string) {
try {
const r: any = await authApi.loginEntities(username)
entities.value = r.data || []
// 默认选中第一个授权企业
if (entities.value.length > 0 && (form.entity_id === undefined || !entities.value.some((e: any) => e.id === form.entity_id))) {
// 切换版:默认选中第一个授权企业;固定企业版:登录时带构建锁定值,不自动改选
if (!fixedMode && entities.value.length > 0 && (form.entity_id === undefined || !entities.value.some((e: any) => e.id === form.entity_id))) {
form.entity_id = entities.value[0].id
}
} catch (_) {
@@ -51,13 +70,14 @@ function onUsernameChange(val: string) {
}
async function handleLogin() {
if (form.entity_id === undefined) {
const entityId = fixedMode ? fixedEntityId : form.entity_id
if (entityId === undefined) {
ElMessage.warning('请选择登录公司')
return
}
loading.value = true
try {
const res: any = await authApi.login({ ...form, entity_id: Number(form.entity_id) })
const res: any = await authApi.login({ ...form, entity_id: Number(entityId) })
localStorage.setItem('cma_token', res.token)
localStorage.setItem('cma_user', JSON.stringify(res.user))
localStorage.setItem('cma_entity_id', String(res.entity_id ?? res.user?.entity_id ?? 1))
@@ -77,6 +97,10 @@ onMounted(() => loadEntities(form.username))
.login-card { background: #fff; padding: 40px; border-radius: 12px; width: 380px; text-align: center; }
.login-card h1 { margin: 0 0 4px; font-size: 24px; }
.subtitle { color: #999; margin-bottom: 24px; }
/* 固定企业版登录徽标 */
.fixed-entity-badge { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; height: 40px; border: 1px dashed #c0c4cc; border-radius: 6px; background: #f8f9fc; padding: 0 12px; }
.fe-label { color: #909399; font-size: 13px; }
.fe-name { color: #303133; font-size: 14px; font-weight: 600; }
@media screen and (max-width: 768px) {
.login-page { padding: 20px; }
.login-card { width: 100%; max-width: 380px; padding: 30px 24px; }
+18 -3
View File
@@ -4,7 +4,10 @@
<div class="report-header">
<h3 class="page-title">📊 CMA管理报表</h3>
<div class="header-right">
<!-- 固定企业版(Phase C):页内切换下拉隐藏,显示当前企业 tag -->
<el-tag v-if="isFixedEntity()" size="small" type="primary" effect="plain">{{ currentEntityNameTag }}</el-tag>
<el-select
v-else
v-model="currentEntityId"
size="small"
style="width:180px"
@@ -624,9 +627,10 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { isFixedEntity, getFixedEntityId } from '../utils/entity'
// ── 状态 ──
const loading = ref(false)
@@ -637,7 +641,17 @@ const reportPeriod = ref('2026-06')
const entities = ref<any[]>([])
const currentEntityId = ref(Number(localStorage.getItem('cma_entity_id') || 1))
// 固定企业版:页内切换下拉隐藏,右上角显示当前企业 tag
const currentEntityNameTag = computed(() => {
const f = getFixedEntityId()
const n = localStorage.getItem('cma_entity_name')
return n || (f !== undefined ? `企业 #${f}` : '')
})
function getEntityId() {
// 固定企业版恒取构建锁定值(防 localStorage 残留串账套);切换版取登录/切换写入值
const f = getFixedEntityId()
if (f !== undefined) return f
return Number(localStorage.getItem('cma_entity_id') || currentEntityId.value || 1)
}
@@ -667,9 +681,10 @@ async function onEntityChange(id: number) {
}
}
// 跨页面同步:其他页面切换企业时联动刷新
// 跨页面同步:其他页面切换企业时联动刷新(固定企业版忽略——该版本不存在切换)
if (typeof window !== 'undefined') {
window.addEventListener('storage', (ev: StorageEvent) => {
if (isFixedEntity()) return
if (ev.key === 'cma_entity_id' && ev.newValue) {
currentEntityId.value = Number(ev.newValue)
loadAll()
@@ -1063,7 +1078,7 @@ function onBudgetSort(sort: any) {
}
onMounted(() => {
loadEntities()
if (!isFixedEntity()) loadEntities()
loadKpiOptions()
loadAll()
loadStatutory()