All checks were successful
Build and Publish / build-release (push) Successful in 2m11s
80 lines
2.3 KiB
TypeScript
80 lines
2.3 KiB
TypeScript
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)?.roles as Record<string, Record<string, string>> | undefined
|
|
if (!allOrgRoles) {
|
|
return []
|
|
}
|
|
|
|
const result: OrganizationInfo[] = []
|
|
for (const [role, orgMap] of Object.entries(allOrgRoles)) {
|
|
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,
|
|
}
|
|
}
|