All files / apps/web/src/hooks useOrganizationInitialization.js

0% Statements 0/30
0% Branches 0/21
0% Functions 0/4
0% Lines 0/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                                                                                                                                                               
import { useEffect, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useOrganizationStore } from '../store/organizationStore'
import { useAuth } from '../contexts/AuthContext'
 
const IS_ORG_ID = /^[0-9a-f]{24}$/
 
/**
 * Guard de navigation global :
 *
 * 1. Fetch les orgs du user si authentifié
 * 2. URL avec orgId :
 *    - Store vide → sync depuis URL
 *    - Store défini (action utilisateur) → le store gagne
 *    - User pas l'orga → redirect vers /
 * 3. URL sans orgId (/ ou /about) :
 *    - Clear store
 *    - Redirect vers /:orgId si user a des orgas
 */
export function useOrganizationInitialization() {
  const location = useLocation()
  const navigate = useNavigate()
  const { isAuthenticated } = useAuth()
  const {
    organizations,
    currentOrganization,
    isLoading,
    fetchOrganizations,
    setCurrentOrganization
  } = useOrganizationStore()
 
  const redirectedRef = useRef(null)
 
  // 1. Fetch organizations on auth
  useEffect(() => {
    if (isAuthenticated) {
      fetchOrganizations()
    }
  }, [isAuthenticated, fetchOrganizations])
 
  // 2. Navigation guard
  useEffect(() => {
    if (!isAuthenticated || isLoading || organizations.length === 0) return
 
    const pathParts = location.pathname.split('/').filter(Boolean)
    const urlOrgId = pathParts[0]
    const hasOrgInUrl = urlOrgId && IS_ORG_ID.test(urlOrgId)
 
    if (hasOrgInUrl) {
      const org = organizations.find(o => o.id === urlOrgId)
      if (org) {
        redirectedRef.current = null
        // Sync store from URL only if store is empty (initial load / refresh)
        // If store is set by user action (createOrganization, switchOrganization), store wins
        if (!currentOrganization) {
          setCurrentOrganization(org)
        }
      } else {
        // Not authorized: redirect to /
        if (redirectedRef.current !== location.pathname) {
          redirectedRef.current = location.pathname
          navigate('/', { replace: true })
        }
      }
    } else {
      // No orgId in URL: clear store
      if (currentOrganization) {
        setCurrentOrganization(null)
      }
      // Bounce to first org if user has orgs
      if (redirectedRef.current !== location.pathname) {
        redirectedRef.current = location.pathname
        navigate(`/${organizations[0].id}${location.pathname}`, { replace: true })
      }
    }
  }, [isAuthenticated, isLoading, organizations, currentOrganization, setCurrentOrganization, location.pathname, navigate])
}
 
export default useOrganizationInitialization