All files / src/components FlowEditSidebar.vue

97.4% Statements 75/77
97.5% Branches 39/40
86.66% Functions 13/15
97.14% Lines 68/70

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                                                                                                      31x 31x 31x 31x 31x 31x                         39x             31x 31x 31x 31x 31x                     31x 33x 2x         31x         3x     31x     38x 34x 34x   6x 4x 2x           6x 6x                   6x       8x 8x 8x 8x       7x 6x 6x 6x 6x                   3x 3x   3x           3x 3x   6x         4x 4x 4x 4x 4x 4x 1x         3x   4x       2x 2x 2x       6x 6x     6x 2x 6x 6x     4x 4x       2x 1x 1x 1x   1x 1x        
<template>
  <FlowFormSidebar
    :is-open="!!editingFlow"
    mode="edit"
    :form-data="flowForm"
    :content-languages="CONTENT_LANGUAGES"
    :loading="formLoading"
    :error="formError"
    :can-update="editingFlow ? hasFlowPermission(editingFlow, 'flows:update') : false"
    :can-delete="editingFlow ? hasFlowPermission(editingFlow, 'flows:delete') : false"
    :flow-id="editingFlow?.flowId"
    @update:form-data="flowForm = $event"
    @close="cancelFlowForm"
    @submit="saveFlow"
    @delete="handleDeleteFlowFromSidebar"
  />
 
  <ConfirmModal
    :is-open="confirmDeleteFlow.open"
    :title="t('flow.deleteFlow')"
    :message="deleteFlowMessage"
    :confirm-label="t('common.delete')"
    :confirm-text="confirmDeleteFlow.flowName"
    variant="danger"
    @confirm="doDeleteFlow"
    @cancel="confirmDeleteFlow.open = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-FLOW-009.1, UC-FLOW-003.1, UC-FLOW-004.1
/**
 * The edit sidebar of one of the user's flows, opened over any page through
 * useFlowEditSidebar() — settings update and Danger Zone delete, each gated by
 * its own permission.
 */
import { ref, reactive, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FlowFormSidebar from '@/components/FlowFormSidebar.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import { useFlowsStore, type FlowMembership } from '@/stores/flows'
import { useToastStore } from '@/stores/toast'
import { useUILanguage } from '@/composables/useUILanguage'
import { hasFlowPermission } from '@/composables/usePermissions'
import { useFlowEditSidebar } from '@/composables/useFlowEditSidebar'
import { CONTENT_LANGUAGES } from '@/utils/languages'
import { getErrorMessage } from '@/utils/errors'
import type { FlowSpace } from '@/utils/spaceTheme'
 
defineOptions({ inheritAttrs: false })
 
const flowsStore = useFlowsStore()
const toastStore = useToastStore()
const route = useRoute()
const router = useRouter()
const { t } = useUILanguage()
const { editedFlowId, closeFlowEdit } = useFlowEditSidebar()
 
type FlowForm = {
  name: string
  slug: string
  defaultLanguage: string
  enabledLanguages: string[]
  description?: string
  picture?: string
  icon?: string
  space?: FlowSpace
}
 
const emptyForm = (): FlowForm => ({
  name: '',
  slug: '',
  defaultLanguage: 'en',
  enabledLanguages: ['en', 'fr']
})
 
const editingFlow = ref<FlowMembership | null>(null)
const flowForm = ref<FlowForm>(emptyForm())
const formLoading = ref(false)
const formError = ref('')
const confirmDeleteFlow = reactive({
  open: false,
  flowId: '',
  flowName: '',
  entitiesToTransferCount: 0
})
 
// Deleting a flow that owns public entities with active external links
// doesn't delete those entities — ownership transfers automatically to their
// top consumer flow (see docs/architecture/PUBLIC_ENTITIES.md). Warn about
// that instead of the plain danger-zone message when transfers would happen.
const deleteFlowMessage = computed(() => {
  if (confirmDeleteFlow.entitiesToTransferCount > 0) {
    return t('flow.deleteWithTransferWarning').replace(
      '{count}',
      String(confirmDeleteFlow.entitiesToTransferCount)
    )
  }
  return t('flow.confirmDeleteFlow')
})
 
// A member can open the sidebar once they hold either permission, not just the owner
function canManageFlow(flow: FlowMembership): boolean {
  return hasFlowPermission(flow, 'flows:update') || hasFlowPermission(flow, 'flows:delete')
}
 
watch(
  editedFlowId,
  (flowId) => {
    if (!flowId) {
      editingFlow.value = null
      return
    }
    const flow = flowsStore.myFlows.find((f) => f.flowId === flowId)
    if (flow && canManageFlow(flow)) startEdit(flow)
    else closeFlowEdit()
  },
  { immediate: true }
)
 
function startEdit(flow: FlowMembership) {
  editingFlow.value = flow
  flowForm.value = {
    name: flow.flowName,
    slug: flow.flowSlug,
    defaultLanguage: flow.defaultLanguage || 'en',
    enabledLanguages: flow.enabledLanguages || ['en', 'fr'],
    description: flow.description,
    picture: flow.picture,
    icon: flow.icon,
    space: flow.space
  }
  formError.value = ''
}
 
function cancelFlowForm() {
  closeFlowEdit()
  editingFlow.value = null
  flowForm.value = emptyForm()
  formError.value = ''
}
 
async function saveFlow() {
  if (!editingFlow.value) return
  formLoading.value = true
  formError.value = ''
  try {
    await flowsStore.updateFlow(editingFlow.value.flowId, {
      name: flowForm.value.name,
      defaultLanguage: flowForm.value.defaultLanguage,
      enabledLanguages: flowForm.value.enabledLanguages,
      description: flowForm.value.description,
      picture: flowForm.value.picture,
      icon: flowForm.value.icon,
      // Sent only once the form touched it: an untouched flow keeps no space
      ...(flowForm.value.space && { space: flowForm.value.space })
    })
    cancelFlowForm()
    toastStore.success(t('flow.updateSuccess'))
  } catch (err: any) {
    console.error('[FlowEditSidebar] saveFlow error:', {
      message: err.message,
      status: err.response?.status,
      data: err.response?.data,
      code: err.code
    })
    formError.value = getErrorMessage(err, 'Failed to update flow', t)
    toastStore.error(t('flow.updateError'))
  } finally {
    formLoading.value = false
  }
}
 
async function startDeleteFlow(flowId: string) {
  const flow = flowsStore.myFlows.find((f) => f.flowId === flowId)
  confirmDeleteFlow.flowId = flowId
  confirmDeleteFlow.flowName = flow?.flowName || ''
  confirmDeleteFlow.entitiesToTransferCount = 0
  try {
    const impact = await flowsStore.fetchFlowDeletionImpact(flowId)
    confirmDeleteFlow.entitiesToTransferCount = impact.entitiesToTransfer.length
  } catch (err) {
    // Non-fatal — worst case the confirmation shows the plain danger-zone
    // message instead of the transfer warning, and the delete call itself
    // still gets a 409 to react to if it turns out entities need transferring.
    console.error('[FlowEditSidebar] failed to fetch deletion impact:', err)
  }
  confirmDeleteFlow.open = true
}
 
async function handleDeleteFlowFromSidebar() {
  const flowId = editingFlow.value?.flowId
  cancelFlowForm()
  if (flowId) await startDeleteFlow(flowId)
}
 
async function doDeleteFlow() {
  confirmDeleteFlow.open = false
  const flowId = confirmDeleteFlow.flowId
  // A page of the deleted flow (its slug in the URL) can't stay open
  const leavesFlowPage =
    !!route.params.flowSlug &&
    flowsStore.myFlows.find((f) => f.flowId === flowId)?.flowSlug === route.params.flowSlug
  try {
    await flowsStore.deleteFlow(flowId, {
      confirmTransfer: confirmDeleteFlow.entitiesToTransferCount > 0
    })
    toastStore.success(t('flow.deleteSuccess'))
    if (leavesFlowPage) await router.push({ name: 'flows' })
  } catch (err: any) {
    // Impact can change between the pre-fetch and this call (e.g. a new link
    // was created in the meantime) — surface a message asking to retry.
    if (err.response?.status === 409 && err.response?.data?.requiresConfirmation) {
      const count = err.response.data.entitiesToTransfer?.length ?? ''
      toastStore.error(t('flow.deleteWithTransferWarning').replace('{count}', String(count)))
      return
    }
    console.error('[FlowEditSidebar] doDeleteFlow error:', err)
    toastStore.error(getErrorMessage(err, t('flow.deleteError')))
  }
}
</script>