All files / apps/web/src/store organizationStore.js

86.36% Statements 38/44
66.66% Branches 12/18
75% Functions 6/8
85% Lines 34/40

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 81 82 83 84 85 86 87 88 89 90      3x                     5x 5x 5x 4x 4x 4x       4x 4x       4x         4x     1x 1x         2x 2x 2x 1x 1x 1x         1x         1x     1x 1x         3x 3x   2x 2x 1x 1x   1x   1x 1x 1x             1x        
import { create } from 'zustand'
import api from '../services/api'
 
export const useOrganizationStore = create((set, get) => ({
  organizations: [],
  currentOrganization: null,
  isLoading: false,
  error: null,
 
  setCurrentOrganization: (org) => {
    set({ currentOrganization: org })
  },
 
  fetchOrganizations: async () => {
    set({ isLoading: true, error: null })
    try {
      const response = await api.get('/auth/me')
      Eif (response.data?.success) {
        const data = response.data.data
        const orgs = data?.organizations || []
        
        // Resynchronise l'organisation courante si elle existe toujours :
        // reflète les changements de rôle (owner ↔ member) côté serveur.
        const currentOrg = get().currentOrganization
        const syncedOrg = currentOrg
          ? orgs.find(o => o.id === currentOrg.id) || currentOrg
          : null
 
        set({
          organizations: orgs,
          currentOrganization: syncedOrg,
          isLoading: false
        })
        return orgs
      }
    } catch (error) {
      console.error('[OrganizationStore] Error fetching organizations:', error)
      set({ error: error.message, isLoading: false })
    }
  },
 
  createOrganization: async (name) => {
    set({ isLoading: true, error: null })
    try {
      const response = await api.post('/organizations', { name })
      Eif (response.data?.success) {
        const newOrg = response.data.data.organization
        const orgWithRole = {
          id: newOrg.id,
          name: newOrg.name,
          role: 'owner'
        }
        set(state => ({
          organizations: [...state.organizations, orgWithRole],
          currentOrganization: orgWithRole,
          isLoading: false
        }))
        return newOrg
      }
    } catch (error) {
      console.error('[OrganizationStore] Error creating organization:', error)
      set({ error: error.message, isLoading: false })
    }
  },
 
  switchOrganization: async (orgId) => {
    const org = get().organizations.find(o => o.id === orgId)
    if (!org) return
 
    try {
      const response = await api.patch('/auth/me', { defaultOrganizationId: orgId })
      Eif (response.data?.token) {
        localStorage.setItem('token', response.data.token)
      }
      set({ currentOrganization: org })
    } catch (error) {
      console.error('[OrganizationStore] Error switching organization:', error)
      const oldToken = localStorage.getItem('token')
      Iif (oldToken) {
        const payload = JSON.parse(atob(oldToken.split('.')[1]))
        if (payload.organizationId) {
          const decoded = oldToken
          localStorage.setItem('token', decoded)
        }
      }
      set({ currentOrganization: org })
    }
  },
}))