File size: 2,036 Bytes
e289c5c 1ef1cda 2ab1980 1ef1cda a966957 e289c5c 2ab1980 e289c5c 2ab1980 e289c5c ef6a2b7 e289c5c 2ab1980 e289c5c 4e2a593 ef6a2b7 2ab1980 ef6a2b7 a966957 ef6a2b7 e289c5c 4e2a593 2ab1980 e289c5c ef6a2b7 e289c5c 2ab1980 e289c5c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import React, { useState, createContext, useContext, useEffect } from 'react';
import { api } from '@/lib/api';
import { Organization } from '@repo/shared-types';
import { useAuth } from '@/lib/auth';
import { logError } from '@/lib/logger';
const TENANT_KEY = 'edtech_selected_org';
interface TenantContextType {
selectedOrgId: string | null;
setSelectedOrgId: (id: string | null) => void;
currentOrg: Organization | null;
isSubdomain: boolean;
slug: string | null;
}
export const TenantContext = createContext<TenantContextType>({
selectedOrgId: null,
setSelectedOrgId: () => {},
currentOrg: null,
isSubdomain: false,
slug: null
});
export function TenantProvider({ children }: { children: React.ReactNode }) {
const { token } = useAuth();
const [selectedOrgId, setSelectedOrgId] = useState<string | null>(() => sessionStorage.getItem(TENANT_KEY));
const [currentOrg, setCurrentOrg] = useState<any | null>(null);
// Subdomain detection logic
const hostname = window.location.hostname;
const parts = hostname.split('.');
const isSubdomain = parts.length > 2 && parts[0] !== 'www' && parts[0] !== 'admin';
const slug = isSubdomain ? parts[0] : null;
useEffect(() => {
if (selectedOrgId && token) {
sessionStorage.setItem(TENANT_KEY, selectedOrgId);
api.get(`/v1/organizations/${selectedOrgId}`, token)
.then(setCurrentOrg)
.catch(err => {
logError("[TENANT] Failed to fetch org details:", err);
setCurrentOrg(null);
});
} else {
if (!selectedOrgId) sessionStorage.removeItem(TENANT_KEY);
setCurrentOrg(null);
}
}, [selectedOrgId, token]);
return (
<TenantContext.Provider value={{ selectedOrgId, setSelectedOrgId, currentOrg, isSubdomain, slug }}>
{children}
</TenantContext.Provider>
);
}
export const useTenant = () => useContext(TenantContext);
|