61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
|
|
import { useAuth0 } from '@auth0/auth0-vue'
|
||
|
|
import { computed, ref, watch } from 'vue'
|
||
|
|
|
||
|
|
import { useOrganizationsQuery } from '~/graphql/generated'
|
||
|
|
|
||
|
|
const selectedOrgId = ref<string | null>(null)
|
||
|
|
|
||
|
|
export const useOrganizationSelector = () => {
|
||
|
|
const auth0 = useAuth0()
|
||
|
|
|
||
|
|
// Fetch user's organizations
|
||
|
|
const { result, loading, error, refetch } = useOrganizationsQuery(() => ({
|
||
|
|
skip: !auth0.isAuthenticated.value,
|
||
|
|
}))
|
||
|
|
|
||
|
|
// Get list of organizations
|
||
|
|
const organizations = computed(() => {
|
||
|
|
return result.value?.organizations || []
|
||
|
|
})
|
||
|
|
|
||
|
|
// Get currently selected organization
|
||
|
|
const selectedOrganization = computed(() => {
|
||
|
|
if (!selectedOrgId.value) return null
|
||
|
|
return organizations.value.find(org => org.id === selectedOrgId.value) || null
|
||
|
|
})
|
||
|
|
|
||
|
|
// Auto-select first organization if none selected
|
||
|
|
watch(organizations, (orgs) => {
|
||
|
|
if (orgs.length > 0 && !selectedOrgId.value) {
|
||
|
|
// Try to restore from localStorage
|
||
|
|
const saved = localStorage.getItem('selectedOrgId')
|
||
|
|
if (saved && orgs.find(o => o.id === saved)) {
|
||
|
|
selectedOrgId.value = saved
|
||
|
|
} else {
|
||
|
|
selectedOrgId.value = orgs[0].id
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}, { immediate: true })
|
||
|
|
|
||
|
|
// Save selection to localStorage
|
||
|
|
watch(selectedOrgId, (newId) => {
|
||
|
|
if (newId) {
|
||
|
|
localStorage.setItem('selectedOrgId', newId)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
const selectOrganization = (orgId: string) => {
|
||
|
|
selectedOrgId.value = orgId
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
organizations,
|
||
|
|
selectedOrganization,
|
||
|
|
selectedOrgId: computed(() => selectedOrgId.value),
|
||
|
|
selectOrganization,
|
||
|
|
loading: loading || ref(false),
|
||
|
|
error: error || ref(null),
|
||
|
|
refetch,
|
||
|
|
}
|
||
|
|
}
|