All files / src/views EntityItemsPage.vue

75.7% Statements 81/107
65.27% Branches 47/72
66.66% Functions 16/24
75.47% Lines 80/106

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              33x 1x     121x               1x       1x                               1x 1x     121x   1x 1x   1x   1x         1x 1x                             4x                                                                                                                       33x 33x 33x 33x 33x   33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x   33x 33x 33x 33x 33x         19x       16x 16x 16x     16x 16x 17x 17x   17x 5x 12x 2x 10x 2x   8x       16x       1x 1x     1x     1x                                   1x       3x 3x 3x 3x 3x       4x 4x   4x 4x 2x   2x   1x   3x       4x       33x 33x 33x     3x 3x       2x 2x 2x   1x                                                                                                                                                                                            
<template>
  <PageLayout
    :title="entity ? getTranslation(entity.name) : t('navigation.entities')"
    class="items-page"
  >
    <template #action>
      <router-link to="/entities" 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">{{
          t('common.backTo').replace('{name}', t('navigation.entities'))
        }}</span>
      </router-link>
      <button
        v-if="itemsStore.items.length > 0"
        class="btn btn-danger me-2"
        :disabled="clearingAll"
        @click="handleClearAll"
      >
        <font-awesome-icon icon="fa-solid fa-trash" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('item.clearAll') }}</span>
      </button>
      <button 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>
    </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="page-header-spacing">
      <div class="container-fluid">
        <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="!initialLoading && itemsStore.items.length === 0" class="row">
          <div class="col-12 text-center py-4">
            <p class="text-muted">{{ t('item.noItems') }}</p>
          </div>
        </div>
      </div>
    </div>
 
    <!-- Virtual scroll list -->
    <VirtualCardGrid
      v-if="!initialLoading && itemsStore.items.length > 0"
      :items="itemsStore.items"
      :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 || []"
          :get-translation="getTranslation"
          @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"
  />
 
  <!-- Clear all items confirmation -->
  <ConfirmModal
    :is-open="confirmClearAll.open"
    :title="t('item.clearAll')"
    :message="t('common.confirmClearAll')"
    :confirm-label="t('item.clearAll')"
    variant="danger"
    @confirm="doClearAll"
    @cancel="confirmClearAll.open = false"
  />
 
  <!-- Clear all success notification -->
  <ConfirmModal
    v-if="clearAllResult"
    :is-open="!!clearAllResult"
    :title="t('common.success')"
    :message="clearAllResult"
    :confirm-label="t('common.close')"
    variant="primary"
    @confirm="clearAllResult = ''"
    @cancel="clearAllResult = ''"
  />
</template>
 
<script setup lang="ts">
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 { useItemsStore } from '@/stores/items'
import { useEntitiesStore, type Entity } from '@/stores/entities'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
 
const route = useRoute()
const itemsStore = useItemsStore()
const entitiesStore = useEntitiesStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
 
const entityId = computed(() => route.params.entityId as string)
const entity = ref<Entity | null>(null)
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 initialLoading = ref(true)
const clearingAll = ref(false)
 
onMounted(async () => {
  initialLoading.value = true
  entity.value = await entitiesStore.fetchEntity(entityId.value)
  await itemsStore.fetchItems(entityId.value)
  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() {
  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) {
  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 = ''
 
  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) {
    formError.value =
      err.response?.data?.error ||
      (editingItemId.value ? 'Failed to update item' : 'Failed to create item')
  } finally {
    formLoading.value = false
  }
}
 
const confirmDeleteItem = reactive({ open: false, itemId: '' })
const confirmClearAll = reactive({ open: false })
const clearAllResult = ref('')
 
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'
  }
}
 
function handleClearAll() {
  confirmClearAll.open = true
}
 
async function doClearAll() {
  confirmClearAll.open = false
  clearingAll.value = true
  try {
    const result = await itemsStore.clearAllItems(entityId.value)
    const deletedItems = result.data?.deletedItems || 0
    const deletedImages = result.data?.deletedImages || 0
    clearAllResult.value = t('item.clearAllSuccess')
      .replace('{deletedItems}', String(deletedItems))
      .replace('{deletedImages}', String(deletedImages))
  } catch (err: any) {
    console.error('Clear all error:', err)
    formError.value = err.response?.data?.error || 'Failed to clear all items'
  } finally {
    clearingAll.value = false
  }
}
</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>