All files / src/stores flows.ts

98.82% Statements 84/85
93.02% Branches 40/43
100% Functions 17/17
98.75% Lines 79/80

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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295                                                                                                            107x 1945x 1945x 1945x 1945x 1945x 1945x   1945x     1945x     33x 33x 33x 33x 4x 4x   11x 11x   15x                   2x 2x 1x 1x   1x                         5x   5x                               5x       2x 2x       1x 1x       265x               265x 265x 265x 265x 265x 252x 265x 1x   251x 251x 251x   4x 1x   3x 4x 4x 4x   256x 254x                     4x 4x 4x 4x       1x   2x                             5x   5x 5x 4x 4x 4x                                 4x     5x       3x 3x 3x   2x 2x   2x 1x         3x     3x   3x 3x 1x                             4x 4x     1945x                                            
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import type { FlowSpace } from '@/utils/spaceTheme'
 
export interface Flow {
  id: string
  name: string
  slug: string
  ownerId: string
  joinPolicy: string
  status: string
  createdAt: string
  defaultLanguage?: string
  enabledLanguages?: string[]
  description?: string
  picture?: string
  icon?: string
  space?: FlowSpace
}
 
export interface FlowMembership {
  flowId: string
  flowName: string
  flowSlug: string
  roleIds: string[]
  permissions: string[]
  status: string
  joinedAt: string
  createdAt?: string
  isOwner: boolean
  defaultLanguage?: string
  enabledLanguages?: string[]
  description?: string
  picture?: string
  icon?: string
  space?: FlowSpace
}
 
export interface FlowMember {
  userId: string
  name?: string
  nickname?: string
  profilePicture?: string | null
  roleIds: string[]
  status: string
  invitedBy?: string
  joinedAt: string
  isOwner: boolean
  /** With a membership entity: the member's item in it, null when none (UC-SPACE-006.2) */
  membershipItemId?: string | null
}
 
export const useFlowsStore = defineStore('flows', () => {
  const myFlows = ref<FlowMembership[]>([])
  const currentFlowMembers = ref<FlowMember[]>([])
  const currentFlowMembersFlowId = ref<string | null>(null)
  const loading = ref(false)
  const membersLoading = ref(false)
  const error = ref<string | null>(null)
  // When the memberships (and so the user's permissions) were last loaded
  const myFlowsLoadedAt = ref(0)
  // Bumped by resetMembers(): a members fetch started before a flow switch
  // must not write the previous flow's members once it resolves.
  let membersGeneration = 0
 
  async function fetchMyFlows() {
    loading.value = true
    error.value = null
    try {
      const response = await api.get('/v1/auth/my-flows')
      myFlows.value = response.data
      myFlowsLoadedAt.value = Date.now()
    } catch (err: any) {
      error.value = err.response?.data?.error || err.message || 'Failed to fetch flows'
      throw err
    } finally {
      loading.value = false
    }
  }
 
  /**
   * Reloads the memberships in the background, when the user's roles may have
   * changed (pushed `permissionsChanged`, or the tab coming back after a while):
   * no loading state, and a failure only keeps the current permissions.
   */
  async function refreshMyFlows() {
    try {
      const response = await api.get('/v1/auth/my-flows')
      myFlows.value = response.data
      myFlowsLoadedAt.value = Date.now()
    } catch (err) {
      console.error('Failed to refresh flows:', err)
    }
  }
 
  async function createFlow(data: {
    id?: string
    name: string
    slug: string
    joinPolicy?: string
    description?: string
    picture?: string
    icon?: 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: [],
      permissions: [],
      status: response.data.status,
      joinedAt: response.data.createdAt,
      createdAt: response.data.createdAt,
      isOwner: true,
      defaultLanguage: response.data.defaultLanguage || 'en',
      enabledLanguages: response.data.enabledLanguages || ['en', 'fr'],
      description: response.data.description,
      picture: response.data.picture,
      icon: response.data.icon
    })
    return response.data
  }
 
  async function inviteUser(flowId: string, nickname: string, roleIds: string[] = []) {
    const response = await api.post(`/v1/flows/${flowId}/invite`, { nickname, 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
    }
 
    const generation = membersGeneration
    membersLoading.value = true
    error.value = null
    try {
      const response = await api.get(`/v1/flows/${flowId}/members`)
      const members = Array.isArray(response?.data) ? response.data : []
      if (generation !== membersGeneration) {
        return members
      }
      currentFlowMembers.value = members
      currentFlowMembersFlowId.value = flowId
      return currentFlowMembers.value
    } catch (err: any) {
      if (generation !== membersGeneration) {
        throw err
      }
      error.value = err.response?.data?.error || err.message || 'Failed to fetch members'
      currentFlowMembers.value = []
      currentFlowMembersFlowId.value = null
      throw err
    } finally {
      if (generation === membersGeneration) {
        membersLoading.value = false
      }
    }
  }
 
  /**
   * Drops the previous active flow's member list on a flow switch, so neither
   * the Members page nor the sidebar badge keeps showing it when the new flow
   * does not grant members:list.
   */
  function resetMembers() {
    membersGeneration++
    currentFlowMembers.value = []
    currentFlowMembersFlowId.value = null
    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[]
      description?: string | null
      picture?: string | null
      icon?: string | null
      space?: FlowSpace
    }
  ) {
    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,
          permissions: currentFlow.permissions,
          status: currentFlow.status,
          joinedAt: currentFlow.joinedAt,
          createdAt: currentFlow.createdAt,
          isOwner: currentFlow.isOwner,
          defaultLanguage: data.defaultLanguage || currentFlow.defaultLanguage,
          enabledLanguages: data.enabledLanguages || currentFlow.enabledLanguages,
          description: response.data.description,
          picture: response.data.picture,
          icon: response.data.icon,
          space: response.data.space
        }
        myFlows.value[flowIndex] = updatedFlow
      }
    }
    return response.data
  }
 
  async function leaveFlow(flowId: string) {
    const authStore = useAuthStore()
    const userId = authStore.userId
    if (!userId) return
 
    await api.delete(`/v1/flows/${flowId}/members/${userId}`)
    myFlows.value = myFlows.value.filter((f) => f.flowId !== flowId)
    // If the flow left was the active one, clear it (the page moves elsewhere)
    if (authStore.currentFlow === flowId) {
      authStore.currentFlow = null
    }
  }
 
  async function deleteFlow(flowId: string, options?: { confirmTransfer?: boolean }) {
    await api.delete(`/v1/flows/${flowId}`, {
      params: options?.confirmTransfer ? { confirmTransfer: true } : undefined
    })
    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
    }
  }
 
  interface FlowDeletionImpactEntity {
    entityId: string
    name: string | Record<string, string>
  }
 
  interface FlowDeletionImpact {
    entitiesToTransfer: (FlowDeletionImpactEntity & { linkedFlowsCount: number })[]
    entitiesToDelete: FlowDeletionImpactEntity[]
  }
 
  async function fetchFlowDeletionImpact(flowId: string): Promise<FlowDeletionImpact> {
    const response = await api.get(`/v1/flows/${flowId}/deletion-impact`)
    return response.data
  }
 
  return {
    myFlows,
    currentFlowMembers,
    currentFlowMembersFlowId,
    loading,
    membersLoading,
    error,
    fetchMyFlows,
    refreshMyFlows,
    myFlowsLoadedAt,
    createFlow,
    inviteUser,
    acceptInvitation,
    fetchMembers,
    resetMembers,
    removeMember,
    updateFlow,
    leaveFlow,
    deleteFlow,
    fetchFlowDeletionImpact
  }
})