This commit is contained in:
81
app/composables/useOrganizationSelection.ts
Normal file
81
app/composables/useOrganizationSelection.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
export interface OrganizationInfo {
|
||||
orgId: string
|
||||
orgDomain: string
|
||||
role: string
|
||||
}
|
||||
|
||||
function extractSubdomain(domain: string): string {
|
||||
const parts = domain.split('.')
|
||||
return parts.length > 1 ? parts[0] : domain
|
||||
}
|
||||
|
||||
|
||||
const STORAGE_KEY = 'policy-ui.selected-org-id'
|
||||
|
||||
export function useOrganizationSelection() {
|
||||
const { data: session } = useAuth()
|
||||
|
||||
const organizations = computed<OrganizationInfo[]>(() => {
|
||||
const allOrgRoles = (session.value?.user as any)?.allOrgRoles as Record<string, Record<string, Record<string, string>>> | undefined
|
||||
if (!allOrgRoles) {
|
||||
return []
|
||||
}
|
||||
|
||||
const result: OrganizationInfo[] = []
|
||||
for (const roles of Object.values(allOrgRoles)) {
|
||||
for (const [role, orgMap] of Object.entries(roles)) {
|
||||
for (const [orgId, orgDomain] of Object.entries(orgMap)) {
|
||||
if (!result.find(o => o.orgId === orgId)) {
|
||||
result.push({ orgId, orgDomain: orgDomain as string, role, orgSubDomain: extractSubdomain(orgDomain) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.sort((a, b) => a.orgDomain.localeCompare(b.orgDomain))
|
||||
return result
|
||||
})
|
||||
|
||||
// All unique org IDs the user has access to
|
||||
const orgIds = computed<string[]>(() => organizations.value.map(o => o.orgId))
|
||||
|
||||
// Persisted selected org
|
||||
const selectedOrgId = ref<string | null>(null)
|
||||
|
||||
onMounted(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
if (stored && orgIds.value.includes(stored)) {
|
||||
selectedOrgId.value = stored
|
||||
} else if (organizations.value.length > 0 && !selectedOrgId.value) {
|
||||
const defaultOrgId = organizations.value[0]!.orgId
|
||||
selectedOrgId.value = defaultOrgId
|
||||
localStorage.setItem(STORAGE_KEY, defaultOrgId)
|
||||
}
|
||||
})
|
||||
|
||||
watch(orgIds, (ids) => {
|
||||
if (ids.length > 0) {
|
||||
const firstId = ids[0]!
|
||||
if (!ids.includes(selectedOrgId.value ?? '')) {
|
||||
selectedOrgId.value = firstId
|
||||
localStorage.setItem(STORAGE_KEY, firstId)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const selectOrg = (orgId: string) => {
|
||||
selectedOrgId.value = orgId
|
||||
localStorage.setItem(STORAGE_KEY, orgId)
|
||||
}
|
||||
|
||||
const selectedOrg = computed<OrganizationInfo | undefined>(() => {
|
||||
if (!selectedOrgId.value) return undefined
|
||||
return organizations.value.find(o => o.orgId === selectedOrgId.value)
|
||||
})
|
||||
|
||||
return {
|
||||
organizations,
|
||||
selectedOrgId,
|
||||
selectedOrg,
|
||||
selectOrg,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user