All files / src/components EntityEditSidebar.vue

91.59% Statements 109/119
84.61% Branches 66/78
72.22% Functions 13/18
91.3% Lines 105/115

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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350                                                                                                                                                                184x                 184x 184x 184x 184x 184x   184x                             197x                     184x 184x 184x 184x 184x 184x 184x 184x 184x 184x         184x             184x   184x 236x 236x 36x             184x 189x 189x 3x   186x       36x 36x                     36x 36x   36x 36x           3x 3x                   35x 35x       1x 1x       13x 13x 13x 13x 13x 13x       20x 20x 20x       20x 20x             20x 20x 1x 1x 1x     19x 19x                             8x 8x 8x   11x 11x   11x           11x 2x         9x 7x     7x   2x   11x   19x         5x       6x 5x       5x 5x 6x 6x 6x 3x 3x 3x         2x 1x       1x 1x   1x 1x 1x         1x       3x 2x 2x 2x 2x 2x 1x         3x   1x 1x 1x   2x       184x    
<template>
  <EntityFormSidebar
    :is-open="!!editingEntity"
    :mode="isViewOnly ? 'view' : 'edit'"
    :form-data="editForm"
    :entity-id="editingEntity?.id"
    :default-language="defaultLanguage"
    :enabled-languages="enabledLanguages"
    :current-language="currentFormLanguage"
    :loading="formLoading"
    :error="formError"
    :name-error="nameError(editForm.name)"
    :field-errors="fieldDefinitionErrors"
    :has-items="editingEntity?.hasItems || false"
    :links-info="editingEntityLinksInfo"
    @update:form-data="editForm = $event"
    @update:current-language="currentFormLanguage = $event"
    @close="cancelEdit"
    @submit="handleUpdateEntity"
    @delete="handleDeleteEntity"
    @clear-all="handleClearAll"
  />
 
  <!-- Delete entity confirmation (type entity name to confirm) -->
  <ConfirmModal
    :is-open="confirmDeleteEntity.open"
    :title="t('entity.deleteEntity')"
    :message="deleteEntityMessage"
    :confirm-label="t('common.delete')"
    :confirm-text="editingEntityName"
    variant="danger"
    @confirm="doDeleteEntity"
    @cancel="confirmDeleteEntity.open = false"
  />
 
  <!-- Clear all items confirmation -->
  <ConfirmModal
    :is-open="confirmClearAll.open"
    :title="t('item.clearAll')"
    :message="t('item.clearAllWarning')"
    :confirm-label="t('item.clearAll')"
    variant="danger"
    @confirm="doClearAll"
    @cancel="confirmClearAll.open = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-004.1, UC-ENTITY-005.1, UC-ENTITY-018.1, UC-ENTITY-019.1, UC-ENTITY-020.1
/**
 * The edit (or read-only inspect) sidebar of an entity, with its Danger Zone
 * (delete, clear all items) — opened over the Entities page and the Items page
 * through the exposed startEdit()/startInspect().
 */
import { ref, reactive, computed } from 'vue'
import EntityFormSidebar from '@/components/EntityFormSidebar.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import {
  useEntitiesStore,
  type Entity,
  type EntityField,
  type WorkflowStateMigration
} from '@/stores/entities'
import { useItemsStore } from '@/stores/items'
import { useToastStore } from '@/stores/toast'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { useEntityFormErrors } from '@/composables/useEntityFormErrors'
import type { VisibilityLevel } from '@/utils/constants'
import {
  validateEntityFields,
  ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY,
  type FieldErrorMap
} from '@/utils/entityValidation'
import { getErrorMessage } from '@/utils/errors'
import { cleanEmailTemplates } from '@/utils/emailTemplates'
import type { EmailTemplate } from '@/schemas/entity-schema'
 
defineOptions({ inheritAttrs: false })
 
const emit = defineEmits<{
  /** The entity was saved; carries the API's updated entity */
  updated: [entity: Entity]
  /** The entity was deleted (or its ownership transferred away) */
  deleted: [entityId: string]
  /** All the entity's items were deleted */
  cleared: [entityId: string]
}>()
 
const entitiesStore = useEntitiesStore()
const itemsStore = useItemsStore()
const toastStore = useToastStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
const { fieldErrorMessage, emailTemplateErrorText, emailTemplatesError, nameError } =
  useEntityFormErrors()
 
type EditForm = {
  name: string | Record<string, string>
  description?: string | Record<string, string>
  visibility: VisibilityLevel
  commentsEnabled?: boolean
  fields: EntityField[]
  forms?: any[]
  emailTemplates?: EmailTemplate[]
  picture?: string
  icon?: string
  workflowStateMigrations?: WorkflowStateMigration[]
}
 
const emptyForm = (): EditForm => ({
  name: '',
  description: undefined,
  visibility: 'flow-members',
  commentsEnabled: false,
  fields: [],
  forms: [],
  picture: undefined,
  icon: undefined
})
 
const isViewOnly = ref(false)
const editingEntity = ref<any>(null)
const editForm = ref<EditForm>(emptyForm())
const currentFormLanguage = ref(defaultLanguage.value)
const formLoading = ref(false)
const formError = ref('')
const fieldDefinitionErrors = ref<FieldErrorMap>({})
const confirmDeleteEntity = reactive({ open: false })
const confirmClearAll = reactive({ open: false })
const clearingAll = ref(false)
 
// Link counts for the entity being edited (only relevant while it's public);
// used to disable switching visibility away from public when other users'
// flows still link this entity.
const editingEntityLinksInfo = ref<{
  sameUserFlowsCount: number
  otherUserFlowsCount: number
  totalFlowsCount: number
} | null>(null)
// In-flight fetch started by populateEditForm, awaited before delete so the
// confirmTransfer decision below never races the fetch (see doDeleteEntity).
let editingEntityLinksInfoPromise: Promise<void> | null = null
 
const editingEntityName = computed(() => {
  const name = editingEntity.value?.name
  if (!name) return ''
  return getTranslation(name)
})
 
// Deleting a public entity with active links doesn't delete it — ownership
// transfers automatically to its top consumer flow (see
// docs/architecture/PUBLIC_ENTITIES.md). Warn about that instead of the
// plain danger-zone message when links exist.
const deleteEntityMessage = computed(() => {
  const totalFlowsCount = editingEntityLinksInfo.value?.totalFlowsCount ?? 0
  if (totalFlowsCount > 0) {
    return t('entity.deleteWithTransferWarning').replace('{count}', String(totalFlowsCount))
  }
  return t('entity.dangerZoneWarning')
})
 
function populateEditForm(entity: any) {
  editingEntity.value = entity
  editForm.value = {
    name: entity.name,
    description: entity.description,
    visibility: entity.visibility || 'flow-members',
    commentsEnabled: entity.commentsEnabled ?? false,
    fields: entity.fields || [],
    forms: entity.forms ?? [],
    emailTemplates: entity.emailTemplates ?? [],
    picture: entity.picture,
    icon: entity.icon
  }
  formError.value = ''
  fieldDefinitionErrors.value = {}
 
  editingEntityLinksInfo.value = null
  editingEntityLinksInfoPromise =
    entity.visibility === 'public'
      ? entitiesStore
          .fetchEntityLinks(entity.id)
          .then((linksInfo) => {
            // Ignore stale responses if the sidebar moved to a different entity meanwhile
            Eif (editingEntity.value?.id === entity.id) {
              editingEntityLinksInfo.value = linksInfo
            }
          })
          .catch(() => {
            // Non-critical: leave linksInfo as null, the backend still enforces the rule on submit
          })
      : null
}
 
function startEdit(entity: any) {
  isViewOnly.value = false
  populateEditForm(entity)
}
 
function startInspect(entity: any) {
  isViewOnly.value = true
  populateEditForm(entity)
}
 
function cancelEdit() {
  editingEntity.value = null
  isViewOnly.value = false
  editForm.value = emptyForm()
  editingEntityLinksInfo.value = null
  formError.value = ''
  fieldDefinitionErrors.value = {}
}
 
async function handleUpdateEntity() {
  formLoading.value = true
  formError.value = ''
  fieldDefinitionErrors.value = {}
 
  // Validate field definitions: known type, well-formed select options,
  // sound number min/max/step, positive length/maxLines
  const definitionErrors = validateEntityFields(editForm.value.fields)
  Iif (Object.keys(definitionErrors).length > 0) {
    fieldDefinitionErrors.value = definitionErrors
    formError.value = t('entity.fixFieldErrors')
    formLoading.value = false
    return
  }
 
  const templateError = emailTemplatesError(editForm.value.emailTemplates, editForm.value.fields)
  if (templateError) {
    formError.value = templateError
    formLoading.value = false
    return
  }
 
  try {
    const updated = await entitiesStore.updateEntity(editingEntity.value.id, {
      name: editForm.value.name,
      fields: editForm.value.fields,
      visibility: editForm.value.visibility,
      commentsEnabled: editForm.value.commentsEnabled ?? false,
      description: editForm.value.description || undefined,
      forms: editForm.value.forms?.length ? editForm.value.forms : undefined,
      // Always sent: an empty list removes the last template
      emailTemplates: cleanEmailTemplates(editForm.value.emailTemplates ?? []),
      picture: editForm.value.picture || undefined,
      icon: editForm.value.icon || undefined,
      workflowStateMigrations: editForm.value.workflowStateMigrations?.length
        ? editForm.value.workflowStateMigrations
        : undefined
    })
    cancelEdit()
    toastStore.success(t('entity.updateSuccess'))
    emit('updated', updated)
  } catch (err: any) {
    const errData = err.response?.data
    Iif (errData?.error === 'MANDATORY_CROSS_FLOW_REFERENCE_NOT_ALLOWED') {
      formError.value = t('entity.mandatoryCrossFlowReference')
    } else Iif (
      ['WORKFLOW_STATE_MIGRATION_REQUIRED', 'INVALID_WORKFLOW_FALLBACK_STATE'].includes(
        errData?.error
      )
    ) {
      formError.value = t('entity.workflowMigrationRequired')
    } else if (errData?.error === 'INVALID_EMAIL_TEMPLATE') {
      formError.value = emailTemplateErrorText(
        errData,
        editForm.value.emailTemplates,
        editForm.value.fields
      )
    } else if (ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY[errData?.error] && errData?.fieldId) {
      fieldDefinitionErrors.value = {
        [errData.fieldId]: ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY[errData.error]
      }
      formError.value = fieldErrorMessage(errData, editForm.value.fields ?? [])
    } else {
      formError.value = getErrorMessage(err, 'Failed to update entity', t)
    }
    toastStore.error(t('entity.updateError'))
  } finally {
    formLoading.value = false
  }
}
 
function handleDeleteEntity() {
  confirmDeleteEntity.open = true
}
 
async function doDeleteEntity() {
  if (!editingEntity.value) return
  confirmDeleteEntity.open = false
  // The links-info fetch triggered on edit-open may still be in flight — wait
  // for it so this doesn't race and send a stale confirmTransfer=false for an
  // entity that actually has active links (see populateEditForm).
  await editingEntityLinksInfoPromise
  const hasActiveLinks = (editingEntityLinksInfo.value?.totalFlowsCount ?? 0) > 0
  const entityId = editingEntity.value.id
  try {
    await entitiesStore.deleteEntity(entityId, { confirmTransfer: hasActiveLinks })
    cancelEdit()
    toastStore.success(t('entity.deleteSuccess'))
    emit('deleted', entityId)
  } catch (err: any) {
    // Link state can change between the pre-fetch and this call (e.g. another
    // flow linked the entity in the meantime) — surface a message asking the
    // user to retry rather than silently failing.
    if (err.response?.status === 409 && err.response?.data?.requiresConfirmation) {
      formError.value = t('entity.deleteWithTransferWarning').replace(
        '{count}',
        String(err.response.data.totalFlowsCount ?? '')
      )
      toastStore.error(t('entity.deleteError'))
      return
    }
    console.error('Delete entity error:', err)
    formError.value = getErrorMessage(err, 'Failed to delete entity')
    toastStore.error(t('entity.deleteError'))
  }
}
 
function handleClearAll() {
  confirmClearAll.open = true
}
 
async function doClearAll() {
  if (!editingEntity.value) return
  confirmClearAll.open = false
  clearingAll.value = true
  const entityId = editingEntity.value.id
  try {
    const response = await itemsStore.clearAllItems(entityId)
    toastStore.success(
      t('item.clearAllSuccess')
        .replace('{deletedItems}', String(response.data?.deletedItems ?? 0))
        .replace('{deletedImages}', String(response.data?.deletedImages ?? 0))
    )
    emit('cleared', entityId)
  } catch (err: any) {
    console.error('Clear all error:', err)
    formError.value = getErrorMessage(err, 'Failed to clear all items')
    toastStore.error(t('item.clearAllError'))
  } finally {
    clearingAll.value = false
  }
}
 
defineExpose({ startEdit, startInspect })
</script>