All files / src/stores tenants.ts

95.74% Statements 45/47
69.56% Branches 16/23
100% Functions 11/11
95.55% Lines 43/45

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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154                                                            22x 540x 540x 540x 540x     3x 3x 3x 3x 3x         3x         4x   4x                       4x 3x   4x       4x   4x     4x       2x 2x       1x 1x       6x 6x 6x 6x 2x   3x 3x 3x   5x         1x   2x             2x   2x 2x 1x 1x 1x                     1x     2x     540x                              
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import { fetchAuthSession } from 'aws-amplify/auth'
 
export interface Tenant {
  id: string
  name: string
  slug: string
  ownerId: string
  joinPolicy: string
  status: string
  createdAt: string
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export interface TenantMembership {
  tenantId: string
  tenantName: string
  tenantSlug: string
  roleIds: string[]
  status: string
  joinedAt: string
  isOwner: boolean
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export const useTenantsStore = defineStore('tenants', () => {
  const myTenants = ref<TenantMembership[]>([])
  const currentTenantMembers = ref<any[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
 
  async function fetchMyTenants() {
    loading.value = true
    error.value = null
    try {
      const response = await api.get('/v1/auth/my-tenants')
      myTenants.value = response.data
    } catch (err: any) {
      error.value = err.response?.data?.error || err.message || 'Failed to fetch tenants'
      throw err
    } finally {
      loading.value = false
    }
  }
 
  async function createTenant(data: { name: string; slug: string; joinPolicy?: string }) {
    const response = await api.post('/v1/tenants', data)
    // Add new tenant to list directly instead of refetching
    myTenants.value.push({
      tenantId: response.data.id,
      tenantName: response.data.name,
      tenantSlug: response.data.slug,
      roleIds: [],
      status: response.data.status,
      joinedAt: response.data.createdAt,
      isOwner: true,
      defaultLanguage: response.data.defaultLanguage || 'en',
      enabledLanguages: response.data.enabledLanguages || ['en', 'fr']
    })
    // Automatically activate the new flow if no current tenant is set
    if (!useAuthStore().currentTenant) {
      await switchTenant(response.data.id)
    }
    return response.data
  }
 
  async function switchTenant(tenantId: string) {
    await api.post('/v1/auth/switch-tenant', { tenantId })
    // Force refresh of auth session to get new token with updated tenantId
    await fetchAuthSession({ forceRefresh: true })
 
    // Reload user to update currentTenant from the new token
    await useAuthStore().loadUser()
  }
 
  async function inviteMember(tenantId: string, email: string, roleIds: string[] = []) {
    const response = await api.post(`/v1/tenants/${tenantId}/invite`, { email, roleIds })
    return response.data
  }
 
  async function acceptInvitation(tenantId: string) {
    await api.post(`/v1/tenants/${tenantId}/accept`)
    await fetchMyTenants()
  }
 
  async function fetchMembers(tenantId: string) {
    loading.value = true
    error.value = null
    try {
      const response = await api.get(`/v1/tenants/${tenantId}/members`)
      currentTenantMembers.value = response.data
    } catch (err: any) {
      error.value = err.response?.data?.error || err.message || 'Failed to fetch members'
      currentTenantMembers.value = []
      throw err
    } finally {
      loading.value = false
    }
  }
 
  async function removeMember(tenantId: string, userId: string) {
    await api.delete(`/v1/tenants/${tenantId}/members/${userId}`)
    // Remove from local list
    currentTenantMembers.value = currentTenantMembers.value.filter((m) => m.userId !== userId)
  }
 
  async function updateTenant(
    tenantId: string,
    data: { name?: string; defaultLanguage?: string; enabledLanguages?: string[] }
  ) {
    const response = await api.put(`/v1/tenants/${tenantId}`, data)
    // Update local tenant in the list - replace the entire object to trigger reactivity
    const tenantIndex = myTenants.value.findIndex((t) => t.tenantId === tenantId)
    if (tenantIndex !== -1) {
      const currentTenant = myTenants.value[tenantIndex]
      Eif (currentTenant) {
        const updatedTenant: TenantMembership = {
          tenantId: currentTenant.tenantId,
          tenantName: data.name || currentTenant.tenantName,
          tenantSlug: currentTenant.tenantSlug,
          roleIds: currentTenant.roleIds,
          status: currentTenant.status,
          joinedAt: currentTenant.joinedAt,
          isOwner: currentTenant.isOwner,
          defaultLanguage: data.defaultLanguage || currentTenant.defaultLanguage,
          enabledLanguages: data.enabledLanguages || currentTenant.enabledLanguages
        }
        myTenants.value[tenantIndex] = updatedTenant
      }
    }
    return response.data
  }
 
  return {
    myTenants,
    currentTenantMembers,
    loading,
    error,
    fetchMyTenants,
    createTenant,
    switchTenant,
    inviteMember,
    acceptInvitation,
    fetchMembers,
    removeMember,
    updateTenant
  }
})