All files / src/stores flows.ts

86.56% Statements 58/67
69.69% Branches 23/33
84.61% Functions 11/13
87.5% Lines 56/64

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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194                                                          25x 640x 640x 640x 640x 640x 640x     3x 3x 3x 3x 3x         3x         6x   6x                           6x 6x 5x 5x       1x   5x   6x       5x       4x 4x 4x   1x   4x       2x 2x       1x 1x       96x               96x 96x 96x 96x 92x 96x 96x   3x 3x 3x 3x   95x         1x   2x             2x   2x 2x 1x 1x 1x                     1x     2x                         640x                                    
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'
 
export interface Flow {
  id: string
  name: string
  slug: string
  ownerId: string
  joinPolicy: string
  status: string
  createdAt: string
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export interface FlowMembership {
  flowId: string
  flowName: string
  flowSlug: string
  roleIds: string[]
  status: string
  joinedAt: string
  isOwner: boolean
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export const useFlowsStore = defineStore('flows', () => {
  const myFlows = ref<FlowMembership[]>([])
  const currentFlowMembers = ref<any[]>([])
  const currentFlowMembersFlowId = ref<string | null>(null)
  const loading = ref(false)
  const membersLoading = ref(false)
  const error = ref<string | null>(null)
 
  async function fetchMyFlows() {
    loading.value = true
    error.value = null
    try {
      const response = await api.get('/v1/auth/my-flows')
      myFlows.value = response.data
    } catch (err: any) {
      error.value = err.response?.data?.error || err.message || 'Failed to fetch flows'
      throw err
    } finally {
      loading.value = false
    }
  }
 
  async function createFlow(data: { name: string; slug: string; joinPolicy?: string }) {
    const response = await api.post('/v1/flows', data)
    // Add new flow to list directly instead of refetching
    myFlows.value.push({
      flowId: response.data.id,
      flowName: response.data.name,
      flowSlug: 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']
    })
    // When no active flow exists, force-refresh the JWT to pick up the new
    // custom:flowId claim, then set currentFlow unconditionally so the UI
    // activates the new flow immediately even if Cognito propagation is slow.
    const authStore = useAuthStore()
    if (!authStore.currentFlow) {
      try {
        await authStore.loadUser(true)
      } catch (e) {
        // Non-fatal: JWT refresh failure is transient; the 401 interceptor will
        // force-refresh on the next API request.
        console.error('[createFlow] JWT refresh failed (non-fatal):', e)
      }
      authStore.currentFlow = response.data.id
    }
    return response.data
  }
 
  async function switchFlow(flowId: string) {
    await api.post('/v1/auth/switch-flow', { flowId })
    // Force-refresh the JWT so it carries the new custom:flowId.
    // Set currentFlow unconditionally after the attempt so the UI activates
    // the new flow even when Cognito propagation is delayed.
    const authStore = useAuthStore()
    try {
      await authStore.loadUser(true)
    } catch (e) {
      console.error('Session refresh failed after flow switch, will retry on next request:', e)
    }
    authStore.currentFlow = flowId
  }
 
  async function inviteUser(flowId: string, email: string, roleIds: string[] = []) {
    const response = await api.post(`/v1/flows/${flowId}/invite`, { email, roleIds })
    return response.data
  }
 
  async function acceptInvitation(flowId: string) {
    await api.post(`/v1/invitations/${flowId}`)
    await fetchMyFlows()
  }
 
  async function fetchMembers(flowId: string, force = false) {
    Iif (
      !force &&
      currentFlowMembersFlowId.value === flowId &&
      currentFlowMembers.value.length > 0
    ) {
      return currentFlowMembers.value
    }
 
    membersLoading.value = true
    error.value = null
    try {
      const response = await api.get(`/v1/flows/${flowId}/members`)
      currentFlowMembers.value = Array.isArray(response?.data) ? response.data : []
      currentFlowMembersFlowId.value = flowId
      return currentFlowMembers.value
    } catch (err: any) {
      error.value = err.response?.data?.error || err.message || 'Failed to fetch members'
      currentFlowMembers.value = []
      currentFlowMembersFlowId.value = null
      throw err
    } finally {
      membersLoading.value = false
    }
  }
 
  async function removeMember(flowId: string, userId: string) {
    await api.delete(`/v1/flows/${flowId}/members/${userId}`)
    // Remove from local list
    currentFlowMembers.value = currentFlowMembers.value.filter((m) => m.userId !== userId)
  }
 
  async function updateFlow(
    flowId: string,
    data: { name?: string; defaultLanguage?: string; enabledLanguages?: string[] }
  ) {
    const response = await api.put(`/v1/flows/${flowId}`, data)
    // Update local flow in the list - replace the entire object to trigger reactivity
    const flowIndex = myFlows.value.findIndex((t) => t.flowId === flowId)
    if (flowIndex !== -1) {
      const currentFlow = myFlows.value[flowIndex]
      Eif (currentFlow) {
        const updatedFlow: FlowMembership = {
          flowId: currentFlow.flowId,
          flowName: data.name || currentFlow.flowName,
          flowSlug: currentFlow.flowSlug,
          roleIds: currentFlow.roleIds,
          status: currentFlow.status,
          joinedAt: currentFlow.joinedAt,
          isOwner: currentFlow.isOwner,
          defaultLanguage: data.defaultLanguage || currentFlow.defaultLanguage,
          enabledLanguages: data.enabledLanguages || currentFlow.enabledLanguages
        }
        myFlows.value[flowIndex] = updatedFlow
      }
    }
    return response.data
  }
 
  async function deleteFlow(flowId: string) {
    await api.delete(`/v1/flows/${flowId}`)
    myFlows.value = myFlows.value.filter((f) => f.flowId !== flowId)
    // If the deleted flow was the active one, clear it
    const authStore = useAuthStore()
    if (authStore.currentFlow === flowId) {
      authStore.currentFlow = null
    }
  }
 
  return {
    myFlows,
    currentFlowMembers,
    currentFlowMembersFlowId,
    loading,
    membersLoading,
    error,
    fetchMyFlows,
    createFlow,
    switchFlow,
    inviteUser,
    acceptInvitation,
    fetchMembers,
    removeMember,
    updateFlow,
    deleteFlow
  }
})