53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import { computed, ref } 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;
|
||
|
|
|
||
|
|
export function useOwnedBusiness() {
|
||
|
|
const auth = useAuthStore();
|
||
|
|
|
||
|
|
async function ensureLoaded() {
|
||
|
|
if (!auth.isBusinessOwner) {
|
||
|
|
ownedBusinessIds.value = new Set();
|
||
|
|
loaded.value = true;
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if (loaded.value) 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;
|
||
|
|
}
|
||
|
|
|
||
|
|
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,
|
||
|
|
};
|
||
|
|
}
|