All files / src/views EntityItemsPage.vue

80.89% Statements 127/157
70.58% Branches 84/119
81.81% Functions 27/33
79.31% Lines 115/145

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        51x 1x 128x             1x       1x                                     1x 1x     128x   1x                 1x 1x             1x   1x         1x 1x                           8x                                                                                             42x 42x 42x 42x 42x 42x           42x 51x 51x 42x 51x       42x 42x 42x 42x           43x 43x 42x       42x 62x       42x 42x         42x 42x 1x                   42x   42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 4x   42x       42x 42x           23x       17x 16x 16x 16x     16x 16x 21x 21x   21x 9x 12x 2x 10x 2x   8x       17x       2x 1x 1x     1x     1x                                   2x       3x 3x 3x 3x 3x       6x 6x     6x 4x                   4x             6x 6x 2x   4x   1x   5x 5x 1x 1x 1x 4x 1x 1x 1x   3x       6x       42x     3x 3x       2x 2x 2x   1x                                                                                                                                                                                
<template>
  <PageLayout :title="entity ? getTranslation(entity.name) : ''" class="items-page">
    <template #action>
      <router-link :to="backLink" class="btn btn-secondary me-2">
        <font-awesome-icon icon="fa-solid fa-arrow-left" class="me-md-2" />
        <span class="d-none d-md-inline">{{ backLabel }}</span>
      </router-link>
      <button
        class="btn btn-outline-secondary me-2 refresh-items-btn"
        :disabled="itemsStore.loading"
        @click="refreshItems"
      >
        <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="canModifyItems" 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('item.createNew') }}</span>
      </button>
      <span v-else class="text-muted small ms-2" style="line-height: 2.5">
        {{ t('item.readOnly') }}
      </span>
    </template>
 
    <ItemFormSidebar
      :is-open="showItemDialog"
      :mode="editingItemId ? 'edit' : 'create'"
      :form-data="itemForm"
      :fields="entity?.fields || []"
      :item-id="editingItemId || tempItemId"
      :default-language="defaultLanguage"
      :enabled-languages="enabledLanguages"
      :current-language="currentFormLanguage"
      :loading="formLoading"
      :error="formError"
      :get-translation="getTranslation"
      @update:form-data="itemForm = $event"
      @update:current-language="currentFormLanguage = $event"
      @close="cancelItemForm"
      @submit="saveItem"
    />
 
    <div class="container-fluid">
      <SearchFilterHeader
        v-model="searchQuery"
        :placeholder="t('item.searchPlaceholder')"
        :filtered-count="filteredCount"
        :total-count="totalCount"
      />
 
      <div v-if="pageError" class="row mb-3">
        <div class="col-12">
          <div class="alert alert-danger mb-0">
            {{ pageError }}
          </div>
        </div>
      </div>
 
      <div v-if="initialLoading" 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="!itemsStore.loading && filteredCount === 0" class="row">
        <div class="col-12 text-center py-4">
          <p class="text-muted">{{ searchQuery ? t('common.noResults') : t('item.noItems') }}</p>
        </div>
      </div>
    </div>
 
    <!-- Virtual scroll list -->
    <VirtualCardGrid
      v-if="!initialLoading"
      :items="filteredItems"
      :has-more="itemsStore.hasMore"
      :is-loading="itemsStore.loading"
      :offset-height="250"
      @load-more="itemsStore.loadMore(entityId)"
    >
      <template #card="{ item }">
        <EntityItemCard
          :item="item"
          :fields="entity?.fields || []"
          :layout="entity?.forms?.[0]?.fields || []"
          :get-translation="getTranslation"
          :can-edit="canModifyItems"
          :can-delete="canModifyItems"
          @edit="startEdit"
          @delete="handleDeleteItem"
        />
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <!-- Delete item confirmation -->
  <ConfirmModal
    :is-open="confirmDeleteItem.open"
    :title="t('item.deleteItem')"
    :message="t('common.confirmDeleteItem')"
    :confirm-label="t('common.delete')"
    variant="danger"
    @confirm="doDeleteItem"
    @cancel="confirmDeleteItem.open = false"
  />
 
  <FloatingPageActions :scroll-top-title="t('common.backToTop')" />
</template>
 
<script setup lang="ts">
// @implements UC-ITEM-001.1, UC-ITEM-002.1, UC-ITEM-003.1, UC-ITEM-004.1, UC-ITEM-005.1, UC-ITEM-006.1, UC-ITEM-007.1
import { ref, onMounted, computed, reactive } from 'vue'
import { useRoute } from 'vue-router'
import PageLayout from '@/components/PageLayout.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import ItemFormSidebar from '@/components/ItemFormSidebar.vue'
import EntityItemCard from '@/components/EntityItemCard.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import FloatingPageActions from '@/components/FloatingPageActions.vue'
import SearchFilterHeader from '@/components/SearchFilterHeader.vue'
import { useItemsStore } from '@/stores/items'
import { useEntitiesStore, type Entity } from '@/stores/entities'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
 
const route = useRoute()
const itemsStore = useItemsStore()
const entitiesStore = useEntitiesStore()
const authStore = useAuthStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
 
function getRequestErrorMessage(err: any, fallback: string) {
  return err?.response?.data?.error || err?.message || fallback
}
 
const entityId = computed(() => route.params.entityId as string)
const openedFromCatalog = computed(() => route.query.source === 'catalog')
const backLink = computed(() => (openedFromCatalog.value ? '/catalog' : '/entities'))
const backLabel = computed(() =>
  openedFromCatalog.value
    ? t('navigation.catalog')
    : t('common.backTo').replace('{name}', t('navigation.entities'))
)
const { searchQuery, appliedQuery, runSearchNow } = useDebouncedSearch(async (query) => {
  try {
    await itemsStore.fetchItems(entityId.value, true, query)
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getRequestErrorMessage(err, 'Failed to load items')
  }
})
 
const filteredCount = computed(() => Math.max(itemsStore.filteredTotal, itemsStore.items.length))
const totalCount = computed(() => Math.max(itemsStore.total, filteredCount.value))
const filteredItems = computed(() => itemsStore.items)
 
// Computed: check if current user can modify items (create/edit/delete)
// Can modify if: entity belongs to current flow OR entity not yet loaded (loading state)
const canModifyItems = computed(() => {
  return entity.value === null || entity.value?.flowId === authStore.currentFlow
})
 
// Synchronous setup before first render — avoid any reactive flip
const _currentEntityId = route.params.entityId as string
const _cachedEntity = entitiesStore.entities.find((e) => e.id === _currentEntityId) ?? null
 
// If items in the store belong to a DIFFERENT entity, clear them now (synchronously)
// so the first render never shows stale data from a previous entity visit.
const _itemsMatchEntity =
  itemsStore.items.length > 0 && itemsStore.items[0]?.entityId === _currentEntityId
if (!_itemsMatchEntity && itemsStore.items.length > 0) {
  itemsStore.$patch({
    items: [],
    hasMore: true,
    nextToken: null,
    filteredTotal: 0,
    total: 0,
    searchQuery: ''
  })
}
 
const entity = ref<Entity | null>(_cachedEntity)
// Show spinner unless we already have items for this exact entity (same-entity revisit)
const initialLoading = ref(!_itemsMatchEntity)
const itemForm = ref<Record<string, any>>({})
const showItemDialog = ref(false)
const editingItemId = ref<string | null>(null)
const tempItemId = ref<string>('')
const currentFormLanguage = ref(defaultLanguage.value)
const formLoading = ref(false)
const formError = ref('')
const pageError = ref('')
 
onMounted(async () => {
  try {
    const fetchedEntity = await entitiesStore.fetchEntity(entityId.value)
    if (fetchedEntity) {
      entity.value = fetchedEntity
    }
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getRequestErrorMessage(err, 'Failed to load entity')
  } finally {
    await runSearchNow()
    initialLoading.value = false
  }
})
 
// Helper to get stable field key for data storage
function getFieldKey(field: { fieldId?: string; name: string | Record<string, string> }): string {
  return field.fieldId!
}
 
function startCreate() {
  if (!canModifyItems.value) return
  showItemDialog.value = true
  editingItemId.value = null
  tempItemId.value = `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
 
  // Initialize itemForm with default values based on field types
  itemForm.value = {}
  entity.value?.fields.forEach((field) => {
    const key = getFieldKey(field)
    const fieldType = field.type || 'text'
 
    if (fieldType === 'text' || fieldType === 'textarea') {
      itemForm.value[key] = {}
    } else if (fieldType === 'boolean') {
      itemForm.value[key] = false
    } else if (fieldType === 'number') {
      itemForm.value[key] = 0
    } else {
      itemForm.value[key] = null
    }
  })
 
  formError.value = ''
}
 
function startEdit(item: any) {
  if (!canModifyItems.value) return
  showItemDialog.value = true
  editingItemId.value = item.id
 
  // Copy item data to form and initialize missing fields with proper defaults
  itemForm.value = { ...item }
 
  // Initialize missing fields based on field definitions
  entity.value?.fields.forEach((field) => {
    const key = getFieldKey(field)
    const fieldType = field.type || 'text'
 
    // Only initialize if field is missing or undefined
    if (itemForm.value[key] === undefined) {
      if (fieldType === 'text' || fieldType === 'textarea') {
        itemForm.value[key] = {}
      } else if (fieldType === 'boolean') {
        itemForm.value[key] = false
      } else if (fieldType === 'number') {
        itemForm.value[key] = 0
      } else {
        itemForm.value[key] = null
      }
    }
  })
 
  formError.value = ''
}
 
function cancelItemForm() {
  showItemDialog.value = false
  editingItemId.value = null
  tempItemId.value = ''
  itemForm.value = {}
  formError.value = ''
}
 
async function saveItem() {
  formLoading.value = true
  formError.value = ''
 
  // Frontend mandatory validation (mirrors backend rules)
  for (const field of entity.value?.fields || []) {
    Eif (!field.mandatory || ['boolean', 'workflow'].includes(field.type || '')) continue
    const key = getFieldKey(field)
    const value = itemForm.value[key]
    const isEmpty =
      value === undefined ||
      value === null ||
      value === '' ||
      (typeof value === 'object' &&
        !Array.isArray(value) &&
        (Object.keys(value).length === 0 || Object.values(value).every((v) => !v || v === '')))
    Iif (isEmpty) {
      formError.value = t('item.fieldRequired').replace('{field}', getTranslation(field.name))
      formLoading.value = false
      return
    }
  }
 
  try {
    if (editingItemId.value) {
      await itemsStore.updateItem(entityId.value, editingItemId.value, itemForm.value)
    } else {
      await itemsStore.createItem(entityId.value, itemForm.value)
    }
    cancelItemForm()
  } catch (err: any) {
    const errData = err.response?.data
    if (errData?.error === 'UNIQUE_FIELD_CONFLICT' && errData?.fieldId) {
      const field = entity.value?.fields.find((f) => f.fieldId === errData.fieldId)
      const fieldName = field ? getTranslation(field.name) : errData.fieldId
      formError.value = t('item.fieldUnique').replace('{field}', fieldName)
    } else if (errData?.error === 'MANDATORY_FIELD_MISSING' && errData?.fieldId) {
      const field = entity.value?.fields.find((f) => f.fieldId === errData.fieldId)
      const fieldName = field ? getTranslation(field.name) : errData.fieldId
      formError.value = t('item.fieldRequired').replace('{field}', fieldName)
    } else {
      formError.value =
        errData?.error || (editingItemId.value ? 'Failed to update item' : 'Failed to create item')
    }
  } finally {
    formLoading.value = false
  }
}
 
const confirmDeleteItem = reactive({ open: false, itemId: '' })
 
function handleDeleteItem(itemId: string) {
  confirmDeleteItem.itemId = itemId
  confirmDeleteItem.open = true
}
 
async function doDeleteItem() {
  confirmDeleteItem.open = false
  try {
    await itemsStore.deleteItem(entityId.value, confirmDeleteItem.itemId)
  } catch (err: any) {
    formError.value = err.response?.data?.error || 'Failed to delete item'
  }
}
 
async function refreshItems() {
  searchQuery.value = appliedQuery.value
 
  try {
    const fetchedEntity = await entitiesStore.fetchEntity(entityId.value)
    if (fetchedEntity) {
      entity.value = fetchedEntity
    }
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getRequestErrorMessage(err, 'Failed to load entity')
  }
 
  await runSearchNow()
}
</script>
 
<style scoped>
/* Remove padding from PageLayout for this page */
.items-page :deep(.page-content) {
  padding: 0 !important;
}
 
/* Add spacing back to header section */
.page-header-spacing {
  padding: 0 2rem;
}
 
pre {
  font-size: 0.85rem;
  max-width: 400px;
  overflow-x: auto;
}
 
/* Mobile optimization */
@media (max-width: 767px) {
  .container-fluid {
    padding: 1rem;
  }
 
  .container-fluid > .row:first-child {
    flex-shrink: 0;
  }
 
  .display-6 {
    font-size: 1.5rem;
  }
 
  .card-header h5 {
    font-size: 1rem;
  }
 
  /* Make textarea and form buttons full width, but not icon buttons */
  .form-control {
    width: 100%;
  }
 
  /* Responsive table */
  .table-responsive {
    font-size: 0.85rem;
  }
 
  .table th,
  .table td {
    padding: 0.5rem;
  }
 
  /* Smaller code blocks on mobile */
  pre {
    font-size: 0.75rem;
    max-width: 250px;
  }
 
  /* Hide Created column on mobile */
  .table th:nth-child(3),
  .table td:nth-child(3) {
    display: none;
  }
 
  .page-header-spacing {
    padding: 0 1rem;
  }
}
</style>