All files / src/views EntitiesPage.vue

90.09% Statements 91/101
85.1% Branches 80/94
76.92% Functions 20/26
90% Lines 90/100

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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405          1x 78x                                       78x     1x 1x 1x   1x       1x               1x   1x 1x 1x                 1x   1x         1x 1x                               2x                                                             35x 35x 35x 35x 35x     35x       11x 2x   10x               35x   35x                             35x 35x 35x                             35x 35x       78x 78x     78x   126x   1x   77x     35x 35x 34x         6x 6x 6x               6x       5x 5x               5x       7x 7x   7x   7x   7x     7x             7x 1x 1x 1x       6x   3x 3x     6x                 7x 4x   2x   7x         8x 8x       4x                           5x 5x               5x       6x 6x   6x   6x   3x 3x     6x               4x   2x   6x       35x     5x 5x       4x 4x 4x   2x                                                                                                                              
<template>
  <PageLayout :title="t('navigation.entities')" class="entities-page">
    <template #action>
      <button v-if="authStore.currentTenant" class="btn btn-success" @click="startCreate">
        <font-awesome-icon icon="fa-solid fa-plus" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('entity.createNew') }}</span>
      </button>
    </template>
 
    <EntityFormSidebar
      :is-open="isCreating || !!editingEntity"
      :mode="isCreating ? 'create' : 'edit'"
      :form-data="isCreating ? newEntity : editForm"
      :item-id="isCreating ? newEntityTempId : editingEntity?.id || ''"
      :entity-id="editingEntity?.id"
      :default-language="defaultLanguage"
      :enabled-languages="enabledLanguages"
      :current-language="currentFormLanguage"
      :loading="formLoading"
      :error="formError"
      :name-error="getNameError()"
      :has-items="editingEntity?.hasItems || false"
      @update:form-data="isCreating ? (newEntity = $event) : (editForm = $event)"
      @update:current-language="currentFormLanguage = $event"
      @close="isCreating ? cancelCreate() : cancelEdit()"
      @submit="isCreating ? handleCreateEntity() : handleUpdateEntity()"
    />
 
    <div v-if="!authStore.currentTenant" class="page-header-spacing">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">
            <div class="alert alert-warning shadow-sm" role="alert">
              <h5 class="alert-heading">{{ t('flow.noActiveFlow') }}</h5>
              <p>{{ t('flow.selectFlowFirst') }}</p>
              <router-link to="/flows" class="btn btn-success">{{
                t('flow.goToFlows')
              }}</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
 
    <div v-if="authStore.currentTenant" class="page-header-spacing">
      <div class="container-fluid">
        <div v-if="storeError" class="row mb-4">
          <div class="col-12">
            <div class="alert alert-danger">
              <h5 class="alert-heading">
                <font-awesome-icon icon="fa-solid fa-exclamation-triangle" class="me-2" />
                {{ t('common.accessDenied') }}
              </h5>
              <p>{{ storeError }}</p>
            </div>
          </div>
        </div>
        <div v-else-if="loading" class="row">
          <div class="col-12 text-center py-4">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">{{ t('common.loading') }}</span>
            </div>
          </div>
        </div>
        <div v-else-if="entitiesStore.entities.length === 0" class="row">
          <div class="col-12 text-center py-4">
            <div class="alert alert-info">
              <p>{{ t('entity.noEntities') }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
 
    <!-- Entity Cards Grid -->
    <VirtualCardGrid
      v-if="authStore.currentTenant && !loading && entitiesStore.entities.length > 0"
      :items="entitiesStore.entities"
      :has-more="entitiesStore.hasMore"
      :is-loading="loading"
      @load-more="entitiesStore.loadMore()"
    >
      <template #card="{ item: entity }">
        <EntityCard :entity="entity" @edit="startEdit" @delete="handleDeleteEntity" />
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <ConfirmModal
    :is-open="confirmDelete.open"
    :title="t('entity.deleteEntity')"
    :message="t('common.confirmDeleteEntity')"
    :confirm-label="t('common.delete')"
    variant="danger"
    @confirm="doDeleteEntity"
    @cancel="confirmDelete.open = false"
  />
</template>
 
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import PageLayout from '@/components/PageLayout.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import EntityCard from '@/components/EntityCard.vue'
import EntityFormSidebar from '@/components/EntityFormSidebar.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import { useEntitiesStore, type EntityField } from '@/stores/entities'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { storeToRefs } from 'pinia'
import { isReservedEntityName, getReservedNameError } from '@/utils/constants'
 
const entitiesStore = useEntitiesStore()
const authStore = useAuthStore()
const { defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
const { loading, error: storeError } = storeToRefs(entitiesStore)
 
// Global language selector for multilingual fields
const currentFormLanguage = ref(defaultLanguage.value)
 
// Helper to check if any translation of a multilingual value is reserved
function isNameReserved(name: string | Record<string, string>): boolean {
  if (typeof name === 'string') {
    return isReservedEntityName(name)
  }
  return Object.values(name).some((val) => isReservedEntityName(val))
}
 
interface FieldForm extends EntityField {
  optionsStr?: string
}
 
// Generate a temporary ID for new entity image uploads
const newEntityTempId = ref(`new-${Date.now()}`)
 
const newEntity = ref<{
  name: string | Record<string, string>
  description?: string | Record<string, string>
  visibility: 'flow-members' | 'restricted' | 'public'
  fields: FieldForm[]
  picture?: string
  icon?: string
}>({
  name: { en: '', fr: '' },
  description: undefined,
  visibility: 'flow-members',
  fields: [],
  picture: undefined,
  icon: undefined
})
const isCreating = ref(false)
const editingEntity = ref<any>(null)
const editForm = ref<{
  name: string | Record<string, string>
  description?: string | Record<string, string>
  visibility: 'flow-members' | 'restricted' | 'public'
  fields: FieldForm[]
  picture?: string
  icon?: string
}>({
  name: { en: '', fr: '' },
  description: undefined,
  visibility: 'flow-members',
  fields: [],
  picture: undefined,
  icon: undefined
})
const formLoading = ref(false)
const formError = ref('')
 
// Helper to get name error message
function getNameError(): string | undefined {
  const data = isCreating.value ? newEntity.value : editForm.value
  Iif (typeof data.name === 'string' && isReservedEntityName(data.name)) {
    return getReservedNameError(data.name)
  }
  if (
    typeof data.name === 'object' &&
    Object.values(data.name).some((val: any) => isReservedEntityName(val))
  ) {
    return 'This name is reserved for system entities'
  }
  return undefined
}
 
onMounted(async () => {
  if (authStore.currentTenant) {
    await entitiesStore.fetchEntities()
  }
})
 
function startCreate() {
  isCreating.value = true
  newEntityTempId.value = `new-${Date.now()}`
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
}
 
function cancelCreate() {
  isCreating.value = false
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
}
 
async function handleCreateEntity() {
  formLoading.value = true
  formError.value = ''
 
  try {
    // Validate entity name is not empty
    const nameValue = newEntity.value.name
    const isEmpty =
      !nameValue ||
      (typeof nameValue === 'string' && !nameValue.trim()) ||
      (typeof nameValue === 'object' && Object.values(nameValue).every((v) => !v?.trim()))
    Iif (isEmpty) {
      formError.value = 'Entity name is required'
      formLoading.value = false
      return
    }
 
    // Validate entity name is not reserved
    if (isNameReserved(newEntity.value.name)) {
      formError.value = 'This name is reserved for system entities'
      formLoading.value = false
      return
    }
 
    // Clean up fields: remove optionsStr and convert to proper format
    const cleanFields = newEntity.value.fields.map((field) => {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { optionsStr, ...cleanField } = field
      return cleanField
    })
 
    const payload = {
      name: newEntity.value.name,
      fields: cleanFields,
      visibility: newEntity.value.visibility,
      ...(newEntity.value.description && { description: newEntity.value.description }),
      ...(newEntity.value.picture && { picture: newEntity.value.picture }),
      ...(newEntity.value.icon && { icon: newEntity.value.icon })
    }
 
    await entitiesStore.createEntity(payload)
    cancelCreate()
  } catch (err: any) {
    formError.value = err.response?.data?.error || 'Failed to create entity'
  } finally {
    formLoading.value = false
  }
}
 
function startEdit(entity: any) {
  editingEntity.value = entity
  editForm.value = {
    name: entity.name,
    description: entity.description,
    visibility: entity.visibility || 'flow-members',
    fields: (entity.fields || []).map((field: EntityField) => ({
      ...field,
      optionsStr: field.options
        ? Array.isArray(field.options)
          ? field.options.join(', ')
          : field.options
        : ''
    })),
    picture: entity.picture,
    icon: entity.icon
  }
}
 
function cancelEdit() {
  editingEntity.value = null
  editForm.value = {
    name: '',
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
}
 
async function handleUpdateEntity() {
  formLoading.value = true
  formError.value = ''
 
  try {
    // Clean up fields: remove optionsStr and convert to proper format
    const cleanFields = editForm.value.fields.map((field) => {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { optionsStr, ...cleanField } = field
      return cleanField
    })
 
    await entitiesStore.updateEntity(editingEntity.value.id, {
      name: editForm.value.name,
      fields: cleanFields,
      visibility: editForm.value.visibility,
      description: editForm.value.description || undefined,
      picture: editForm.value.picture || undefined,
      icon: editForm.value.icon || undefined
    })
    cancelEdit()
  } catch (err: any) {
    formError.value = err.response?.data?.error || 'Failed to update entity'
  } finally {
    formLoading.value = false
  }
}
 
const confirmDelete = reactive({ open: false, id: '' })
 
function handleDeleteEntity(id: string) {
  confirmDelete.id = id
  confirmDelete.open = true
}
 
async function doDeleteEntity() {
  confirmDelete.open = false
  try {
    await entitiesStore.deleteEntity(confirmDelete.id)
  } catch (err: any) {
    formError.value = err.response?.data?.error || 'Failed to delete entity'
  }
}
</script>
 
<style scoped>
/* Remove padding from PageLayout for this page */
.entities-page :deep(.page-content) {
  padding: 0 !important;
}
 
.card {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}
 
/* Add spacing back to header section */
.page-header-spacing {
  padding: 0 2rem;
}
 
/* Scrollable edit form */
.border-primary .card-body {
  max-height: 70vh;
  overflow-y: auto;
}
 
.default-picture {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 3rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}
 
/* Mobile optimization */
@media (max-width: 767px) {
  .page-header-spacing {
    padding: 0 1rem;
  }
 
  .display-6 {
    font-size: 1.5rem;
  }
 
  .card-header h5 {
    font-size: 1rem;
  }
 
  /* Stack form fields vertically */
  .row.g-3 {
    row-gap: 0.75rem !important;
  }
 
  /* Form buttons can be full width, but not action buttons */
  .card .btn {
    width: 100%;
    margin-top: 0.5rem;
  }
}
</style>