All files / src/views EntitiesPage.vue

78.16% Statements 111/142
73.84% Branches 96/130
65.78% Functions 25/38
77.94% Lines 106/136

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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536                  1x 80x             1x                                             80x     1x 1x 1x   1x       1x                               1x 1x 1x                 1x   1x         1x 1x                             2x                                                                                                                 34x 34x 34x 34x 34x 34x 34x 34x 33x     34x 33x   34x   34x     34x       11x 2x   10x               34x   34x                                 34x 34x 34x                                 34x 34x 34x   34x 54x 54x 11x         80x 80x     80x   124x   1x   79x     34x 34x 33x                   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         11x 11x       4x                             6x 6x                 6x       6x 6x   6x   6x   3x 3x     6x                 4x   2x           6x                                                                 3x       3x 2x 2x 2x 1x   1x 1x       34x 34x                                                                                                                                                    
<template>
  <PageLayout :title="t('navigation.entities')" class="entities-page">
    <template #action>
      <button
        class="btn btn-outline-secondary me-2 refresh-entities-btn"
        :disabled="loading"
        @click="refreshEntities"
      >
        <font-awesome-icon icon="fa-solid fa-rotate-right" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('common.refresh') }}</span>
      </button>
      <button
        v-if="authStore.currentFlow && hasPermission('entity:create')"
        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()"
      @delete="handleDeleteEntity"
      @clear-all="handleClearAll"
    />
 
    <div v-if="!authStore.currentFlow" 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.currentFlow" class="container-fluid">
      <SearchFilterHeader
        v-model="searchQuery"
        :placeholder="t('entity.searchPlaceholder')"
        :filtered-count="filteredCount"
        :total-count="totalCount"
      />
 
      <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="filteredCount === 0" class="row">
        <div class="col-12 text-center py-4">
          <div class="alert alert-info">
            <p>{{ searchQuery ? t('common.noResults') : t('entity.noEntities') }}</p>
          </div>
        </div>
      </div>
    </div>
 
    <!-- Entity Cards Grid -->
    <VirtualCardGrid
      v-if="authStore.currentFlow && !loading && filteredCount > 0"
      :items="filteredEntities"
      :has-more="entitiesStore.hasMore"
      :is-loading="loading"
      @load-more="entitiesStore.loadMore()"
    >
      <template #card="{ item: entity }">
        <EntityCard
          :entity="entity"
          @edit="startEdit"
          @fork="handleForkEntity"
          @unlink="handleUnlinkEntity"
        />
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <!-- Delete entity confirmation (type entity name to confirm) -->
  <ConfirmModal
    :is-open="confirmDeleteEntity.open"
    :title="t('entity.deleteEntity')"
    :message="t('entity.dangerZoneWarning')"
    :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"
  />
 
  <FloatingPageActions :scroll-top-title="t('common.backToTop')" />
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-001.1, UC-ENTITY-002.1, UC-ENTITY-003.1, UC-ENTITY-004.1, UC-ENTITY-005.1, UC-ENTITY-006.1, UC-ENTITY-007.1, UC-ENTITY-009.1
import { ref, onMounted, reactive, computed } 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 FloatingPageActions from '@/components/FloatingPageActions.vue'
import SearchFilterHeader from '@/components/SearchFilterHeader.vue'
import { useEntitiesStore, type EntityField } from '@/stores/entities'
import { useItemsStore } from '@/stores/items'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { usePermissions } from '@/composables/usePermissions'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
import { storeToRefs } from 'pinia'
import { isReservedEntityName, getReservedNameError } from '@/utils/constants'
 
const entitiesStore = useEntitiesStore()
const itemsStore = useItemsStore()
const authStore = useAuthStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
const { hasPermission } = usePermissions()
const { loading, error: storeError } = storeToRefs(entitiesStore)
const { searchQuery, appliedQuery, runSearchNow } = useDebouncedSearch(async (query) => {
  await entitiesStore.fetchEntities(true, query)
})
 
const filteredCount = computed(() =>
  Math.max(entitiesStore.filteredTotal, entitiesStore.entities.length)
)
const totalCount = computed(() => Math.max(entitiesStore.total, filteredCount.value))
 
const filteredEntities = computed(() => entitiesStore.entities)
 
// 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' | 'public'
  fields: FieldForm[]
  forms?: any[]
  picture?: string
  icon?: string
}>({
  name: { en: '', fr: '' },
  description: undefined,
  visibility: 'flow-members',
  fields: [],
  forms: [],
  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' | 'public'
  fields: FieldForm[]
  forms?: any[]
  picture?: string
  icon?: string
}>({
  name: { en: '', fr: '' },
  description: undefined,
  visibility: 'flow-members',
  fields: [],
  forms: [],
  picture: undefined,
  icon: undefined
})
const formLoading = ref(false)
const formError = ref('')
const confirmDeleteEntity = reactive({ open: false })
 
const editingEntityName = computed(() => {
  const name = editingEntity.value?.name
  if (!name) return ''
  return getTranslation(name)
})
 
// 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.currentFlow) {
    await runSearchNow()
  }
})
 
async function refreshEntities() {
  searchQuery.value = appliedQuery.value
  await runSearchNow()
}
 
function startCreate() {
  isCreating.value = true
  newEntityTempId.value = `new-${Date.now()}`
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    forms: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
}
 
function cancelCreate() {
  isCreating.value = false
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    forms: [],
    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.forms?.length && { forms: newEntity.value.forms }),
      ...(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 ||
      err.response?.data?.message ||
      err.message ||
      '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
        : ''
    })),
    forms: entity.forms ?? [],
    picture: entity.picture,
    icon: entity.icon
  }
}
 
function cancelEdit() {
  editingEntity.value = null
  editForm.value = {
    name: '',
    description: undefined,
    visibility: 'flow-members',
    fields: [],
    forms: [],
    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,
      forms: editForm.value.forms?.length ? editForm.value.forms : undefined,
      picture: editForm.value.picture || undefined,
      icon: editForm.value.icon || undefined
    })
    cancelEdit()
  } catch (err: any) {
    formError.value =
      err.response?.data?.error ||
      err.response?.data?.message ||
      err.message ||
      'Failed to update entity'
  } finally {
    formLoading.value = false
  }
}
 
async function handleForkEntity(entity: any) {
  try {
    const sourceName = getTranslation(entity.name)
    await entitiesStore.forkEntity(entity.id, {
      name: `${sourceName} (Fork)`,
      visibility: 'flow-members'
    })
  } catch (err: any) {
    formError.value =
      err.response?.data?.error ||
      err.response?.data?.message ||
      err.message ||
      'Failed to fork entity'
  }
}
 
async function handleUnlinkEntity(entity: any) {
  try {
    await entitiesStore.unlinkEntity(entity.id)
  } catch (err: any) {
    formError.value =
      err.response?.data?.error ||
      err.response?.data?.message ||
      err.message ||
      'Failed to unlink entity'
  }
}
 
function handleDeleteEntity() {
  confirmDeleteEntity.open = true
}
 
async function doDeleteEntity() {
  if (!editingEntity.value) return
  confirmDeleteEntity.open = false
  try {
    await entitiesStore.deleteEntity(editingEntity.value.id)
    cancelEdit()
  } catch (err: any) {
    console.error('Delete entity error:', err)
    formError.value = err.response?.data?.error || err.message || 'Failed to delete entity'
  }
}
 
const confirmClearAll = reactive({ open: false })
const clearingAll = ref(false)
 
function handleClearAll() {
  confirmClearAll.open = true
}
 
async function doClearAll() {
  if (!editingEntity.value) return
  confirmClearAll.open = false
  clearingAll.value = true
  try {
    await itemsStore.clearAllItems(editingEntity.value.id)
  } catch (err: any) {
    console.error('Clear all error:', err)
    formError.value = err.response?.data?.error || err.message || 'Failed to clear all items'
  } finally {
    clearingAll.value = false
  }
}
</script>
 
<style scoped>
/* Remove padding from PageLayout for this page */
.entities-page :deep(.page-content) {
  padding: 0 !important;
}
 
/* 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>