72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import { computed, ref, watch } from 'vue';
|
|
import { fetchMyBusinesses } from '@/api/businesses';
|
|
import { useAuthStore } from '@/stores/auth';
|
|
|
|
const ownedBusinessIds = ref<Set<string>>(new Set());
|
|
const loaded = ref(false);
|
|
let loadPromise: Promise<void> | null = null;
|
|
let authWatchStarted = false;
|
|
|
|
export function useOwnedBusiness() {
|
|
const auth = useAuthStore();
|
|
|
|
async function ensureLoaded(force = false) {
|
|
if (auth.token && !auth.user) {
|
|
await auth.loadUser();
|
|
}
|
|
|
|
if (!auth.isLoggedIn || !auth.isBusinessOwner) {
|
|
ownedBusinessIds.value = new Set();
|
|
loaded.value = true;
|
|
loadPromise = null;
|
|
return;
|
|
}
|
|
|
|
if (loaded.value && !force) return;
|
|
if (loadPromise) {
|
|
await loadPromise;
|
|
return;
|
|
}
|
|
|
|
loadPromise = (async () => {
|
|
try {
|
|
const businesses = await fetchMyBusinesses();
|
|
ownedBusinessIds.value = new Set(businesses.map((item) => item.id));
|
|
} catch {
|
|
ownedBusinessIds.value = new Set();
|
|
} finally {
|
|
loaded.value = true;
|
|
loadPromise = null;
|
|
}
|
|
})();
|
|
|
|
await loadPromise;
|
|
}
|
|
|
|
if (!authWatchStarted) {
|
|
authWatchStarted = true;
|
|
watch(
|
|
() => [auth.token, auth.user?.id, auth.user?.role] as const,
|
|
() => {
|
|
loaded.value = false;
|
|
loadPromise = null;
|
|
void ensureLoaded(true);
|
|
},
|
|
);
|
|
}
|
|
|
|
function isOwnBusiness(businessId: string | null | undefined): boolean {
|
|
if (!businessId || !auth.isBusinessOwner) return false;
|
|
return ownedBusinessIds.value.has(businessId);
|
|
}
|
|
|
|
const ownsAnyBusiness = computed(() => ownedBusinessIds.value.size > 0);
|
|
|
|
return {
|
|
loaded,
|
|
ownsAnyBusiness,
|
|
ensureLoaded,
|
|
isOwnBusiness,
|
|
};
|
|
}
|