import { computed, ref } from 'vue' import { defineStore } from 'pinia' import { expandRoles, fetchRoleDict, getMyProfile, type TrainingRoleDef, } from '@/api/training' import { useAuthStore } from '@/stores/auth' /** * 当前登录用户在培训域的职称角色与「超级管理员」统一判定。 * * 职称角色(hr/课长/讲师/经理/super_admin…)挂在组织中心的员工档案上 * (org_module_members,module_key='training'),经 /training/members/me * 返回;原先是 Training.vue 页面内局部状态,权限收口(000167)后头像菜单 * 与设置页入口也需要它,因此上移为全局 store。 * * isSuperAdmin 统一口径:培训职称角色=超级管理员,或平台超管 * (is_system_admin / 跨空间超管 can_access_all_tenants)——平台超管不因 * 未分配职称而被锁在系统管理之外。 */ export const useTrainingRolesStore = defineStore('trainingRoles', () => { const authStore = useAuthStore() /** 原始分配角色(未展开继承),与 Training.vue 的 rawRoles 同源 */ const rawRoles = ref([]) /** 职称角色字典(配置中心可配) */ const roleDict = ref([]) /** 已成功加载的空间标识(selectedTenantId),避免重复拉取 */ const loadedForTenant = ref('') const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value)) const isTrainingSuperAdmin = computed(() => myRoles.value.includes('super_admin')) // Lite 模式无 RBAC/职称概念(单用户本地部署),保持原有入口可见性。 const isSuperAdmin = computed( () => authStore.isLiteMode || authStore.isSystemAdmin || authStore.canAccessAllTenants || isTrainingSuperAdmin.value, ) const currentTenantKey = () => { const id = authStore.selectedTenantId ?? authStore.tenant?.id return id != null ? String(id) : '' } let inflight: Promise | null = null /** * 确保本人档案已按当前空间加载。失败(培训模块不可用/未入档/会话问题) * 按「无职称」降级并同样缓存 —— 入口隐藏、平台超管不受影响;分配职称后 * 刷新页面或调 reload() 生效,避免失败时每次挂载都打接口。 */ const ensureLoaded = async (): Promise => { const tenantKey = currentTenantKey() if (!tenantKey || loadedForTenant.value === tenantKey) return if (inflight) return inflight inflight = (async () => { try { const [profileRes, dict] = await Promise.all([ getMyProfile() as unknown as { data?: unknown }, fetchRoleDict(), ]) // 兼容两种封包:拦截器解包后 {success, data}(data 即 member) const payload = (profileRes as { data?: { data?: unknown } })?.data const member = (payload as { data?: unknown })?.data ?? payload rawRoles.value = ((member as { roles?: string[] })?.roles) || ['trainee'] roleDict.value = dict loadedForTenant.value = tenantKey } catch { rawRoles.value = [] roleDict.value = [] loadedForTenant.value = tenantKey } finally { inflight = null } })() return inflight } /** 显式重取(如组织架构刚给自己分配/回收职称后) */ const reload = async (): Promise => { loadedForTenant.value = '' await ensureLoaded() } return { rawRoles, roleDict, myRoles, isTrainingSuperAdmin, isSuperAdmin, ensureLoaded, reload } })