import { buildRuntimeMenuTree, type NavMenuLayoutConfig, type RuntimeMenuItem, } from './menuLayout'; import { MENU_CATALOG } from '../config/menuCatalog'; import { loadNavMenuLayoutForScope } from './menuLayoutLoad'; import { resolveSidebarMenuScope } from './menuLayoutBranch'; export interface CachedSidebarMenu { layout: NavMenuLayoutConfig; menuItems: RuntimeMenuItem[]; fromDirectRecord: boolean; } interface StoredSidebarMenu { layout: NavMenuLayoutConfig; fromDirectRecord: boolean; /** 写入缓存时的菜单目录指纹(见 catalogSignature) */ catalogSignature?: string; } /** * **布局模板版本**:改动"顶层结构/分组归属"时必须 +1 —— 它参与 `catalogSignature()`, * 从而让所有端(含老会话的 sessionStorage)**重建一次**。 * 为什么单独要它:`catalogSignature` 只看菜单目录的 key 列表,**结构变化它察觉不到** * ⇒ 不加就会出现"代码已按主系统模板收敛,用户界面仍是旧的 11 个顶层"。 * v2 = 2026-10-27 按主系统模板收敛(顶层只留 数据看板/订单录入 + 业务流程/基础数据/财务结算/系统管理)。 */ export const LAYOUT_TEMPLATE_VERSION = 'v2'; const SESSION_STORAGE_KEY = 'nav-sidebar-menu-cache-v2'; const cache = new Map(); const inflight = new Map>(); /** * 菜单目录指纹:目录(MENU_CATALOG)一变,指纹就变 ⇒ 旧缓存自动作废。 * * 为什么需要它(2026-10-11 实测):侧边栏把"合并后的布局"缓存在 sessionStorage,**无 TTL**; * 新版本加了菜单项时,老会话里的缓存仍是没有该项的旧布局 ⇒ 用户看不到新入口 * (刷新也不会好,因为 sessionStorage 跨刷新存在)。 */ export function catalogSignature(): string { return `${LAYOUT_TEMPLATE_VERSION}::${MENU_CATALOG.map((entry) => entry.menuKey).sort().join('|')}`; } export function sidebarMenuCacheKey(profileId: string, scope: string): string { return `${profileId}:${scope}`; } function createCacheEntry(layout: NavMenuLayoutConfig, fromDirectRecord: boolean): CachedSidebarMenu { return { layout, menuItems: buildRuntimeMenuTree(layout), fromDirectRecord, }; } function readSessionCache(key: string): CachedSidebarMenu | undefined { try { const raw = sessionStorage.getItem(SESSION_STORAGE_KEY); if (!raw) return undefined; const all = JSON.parse(raw) as Record; const entry = all[key]; if (!entry?.layout) return undefined; // 目录变了(发过新版)⇒ 视为未命中,强制重新拉取并按新默认布局合并。 // 没有指纹的条目 = 本次修复之前写入的旧缓存,同样作废(否则老会话仍看不到新菜单)。 if (entry.catalogSignature !== catalogSignature()) return undefined; return createCacheEntry(entry.layout, Boolean(entry.fromDirectRecord)); } catch { return undefined; } } function writeSessionCache(key: string, entry: CachedSidebarMenu) { try { const raw = sessionStorage.getItem(SESSION_STORAGE_KEY); const all = raw ? (JSON.parse(raw) as Record) : {}; all[key] = { layout: entry.layout, fromDirectRecord: entry.fromDirectRecord, catalogSignature: catalogSignature(), }; sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(all)); } catch { // ignore quota / private mode failures } } export function readSidebarMenuCache(key: string): CachedSidebarMenu | undefined { const memoryHit = cache.get(key); if (memoryHit) return memoryHit; const sessionHit = readSessionCache(key); if (sessionHit) { cache.set(key, sessionHit); return sessionHit; } return undefined; } export function isSidebarMenuInflight(key: string): boolean { return inflight.has(key); } export function clearSidebarMenuCache(): void { cache.clear(); inflight.clear(); try { sessionStorage.removeItem(SESSION_STORAGE_KEY); sessionStorage.removeItem('nav-sidebar-menu-cache-v1'); } catch { // ignore } } export async function fetchSidebarMenuCached( profileId: string, scope: string ): Promise { const key = sidebarMenuCacheKey(profileId, scope); const hit = readSidebarMenuCache(key); if (hit) return hit; const pending = inflight.get(key); if (pending) return pending; const promise = loadNavMenuLayoutForScope(scope) .then(({ layout, fromDirectRecord }) => { const entry = createCacheEntry(layout, fromDirectRecord); cache.set(key, entry); writeSessionCache(key, entry); return entry; }) .finally(() => { inflight.delete(key); }); inflight.set(key, promise); return promise; } /** 登录/会话恢复时预加载侧边栏菜单,避免 Layout 首次渲染出现骨架屏闪烁 */ export async function prefetchSidebarMenuForProfile(profile: { id: string; branch_code: string | null; roles: string[]; }): Promise { const isSuperAdmin = profile.roles.includes('super_admin'); const scope = resolveSidebarMenuScope(isSuperAdmin, profile.branch_code); try { await fetchSidebarMenuCached(profile.id, scope); } catch (error) { console.error('预加载导航菜单失败:', error); } }