All files / src/views CatalogPage.vue

82.92% Statements 68/82
72.97% Branches 27/37
92.59% Functions 25/27
85.52% Lines 65/76

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                  1x 30x     1x   3x                           20x     30x                       11x                   1x   18x       4x   2x 1x                                           1x                                                               17x 17x 17x 17x 17x   17x 3x     17x 17x 17x   17x 21x     17x     17x   17x   17x           1x             1x 1x           17x 17x       1x 1x       13x       17x                                 4x 4x 4x 4x 4x       3x 3x   3x 3x   3x 3x           3x   3x     3x   3x     3x         3x                               2x 2x 2x 1x   1x 1x         1x 1x 1x 1x                                                                                                                            
<template>
  <PageLayout :title="t('catalog.title')" class="catalog-page">
    <template #action>
      <button
        class="btn btn-outline-secondary refresh-catalog-btn"
        :disabled="loading"
        @click="refreshCatalog"
      >
        <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>
    </template>
 
    <div class="container-fluid">
      <SearchFilterHeader
        v-model="searchQuery"
        data-tour="catalog-search"
        :placeholder="t('catalog.search-placeholder')"
        :filtered-count="filteredCount"
        :total-count="totalCount"
      >
        <template #extra>
          <SortControl
            :options="catalogSortOptions"
            :field-value="catalogStore.sort?.fieldId || DEFAULT_CATALOG_SORT.fieldId"
            :direction="catalogStore.sort?.direction || 'asc'"
            :label="t('common.sortBy')"
            @update:field-value="handleSortFieldChange"
            @toggle-direction="handleSortDirectionToggle"
          />
        </template>
      </SearchFilterHeader>
    </div>
 
    <!-- Loading state -->
    <LoadingSpinner
      v-if="loading && catalogStore.entities.length === 0"
      :grid="false"
      :padding="5"
      :message="t('common.loading')"
    />
 
    <!-- Empty state -->
    <EmptyState v-else-if="filteredCount === 0" variant="info">
      {{ searchQuery ? t('common.noResults') : t('catalog.no-public-entities') }}
    </EmptyState>
 
    <!-- Entities grid -->
    <VirtualCardGrid
      v-else
      :items="filteredEntities"
      :has-more="catalogStore.hasMore"
      :is-loading="loading"
      :offset-height="280"
      @load-more="catalogStore.loadMore()"
    >
      <template #card="{ item: entity }">
        <EntityCard
          :entity="entity"
          navigation-source="catalog"
          @fork="handleFork(entity)"
          @link="handleLink(entity)"
          @subscribe="handleSubscribe(entity)"
          @unsubscribe="handleUnsubscribe(entity)"
        />
      </template>
    </VirtualCardGrid>
 
    <!-- Error message -->
    <div v-if="catalogStore.error" class="alert alert-danger mt-4" role="alert">
      <font-awesome-icon icon="fa-solid fa-exclamation-triangle" class="me-2" />
      {{ catalogStore.error }}
    </div>
  </PageLayout>
 
  <ForkEntityModal
    :is-open="forkModal.open"
    :entity-id="forkModal.entity?.id ?? ''"
    :entity-name="forkModal.entityName"
    :default-name="forkModal.defaultName"
    :loading="forkModal.loading"
    :error="forkModal.error"
    :status="forkJob.status.value"
    :progress="forkJob.progress.value"
    @confirm="confirmFork"
    @cancel="forkModal.open = false"
  />
 
  <FloatingPageActions :scroll-top-title="t('common.backToTop')" />
</template>
 
<script setup lang="ts">
// @implements UC-CATALOG-001.1, UC-CATALOG-002.1, UC-CATALOG-003.1, UC-CATALOG-004.1, UC-CATALOG-005.1, UC-CATALOG-006.1, UC-ENTITY-010.1, UC-ENTITY-011.1, UC-ENTITY-012.1, UC-ENTITY-013.1
import { onMounted, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useCatalogStore, DEFAULT_CATALOG_SORT, type CatalogSort } from '@/stores/catalog'
import { useEntitiesStore } from '@/stores/entities'
import { useUILanguage } from '@/composables/useUILanguage'
import { useForkJob } from '@/composables/useForkJob'
import { renamedFieldsText } from '@/utils/renamedFields'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
import { useFilteredCounts } from '@/composables/useFilteredCounts'
import { storeToRefs } from 'pinia'
import PageLayout from '@/components/PageLayout.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import EntityCard from '@/components/EntityCard.vue'
import FloatingPageActions from '@/components/FloatingPageActions.vue'
import SearchFilterHeader from '@/components/SearchFilterHeader.vue'
import SortControl, { type SortOption } from '@/components/SortControl.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import ForkEntityModal from '@/components/ForkEntityModal.vue'
import type { Entity } from '@/stores/entities'
import { useToastStore } from '@/stores/toast'
import { getErrorMessage } from '@/utils/errors'
import { useFlowLink } from '@/composables/useFlowLink'
 
const router = useRouter()
const { flowLink } = useFlowLink()
const catalogStore = useCatalogStore()
const entitiesStore = useEntitiesStore()
const forkJob = useForkJob()
// The fork renames a field whose name an earlier field has (UC-ENTITY-029.1)
const withRenamedFields = (message: string) =>
  forkJob.renamedFields.value.length > 0
    ? `${message}. ${renamedFieldsText(t, forkJob.renamedFields.value)}`
    : message
const toastStore = useToastStore()
const { t } = useUILanguage()
const { loading, filteredTotal, total: storeTotal } = storeToRefs(catalogStore)
 
const { searchQuery, appliedQuery, runSearchNow } = useDebouncedSearch(async (query) => {
  await catalogStore.fetchCatalog(query)
})
 
const { filteredCount, totalCount } = useFilteredCounts(
  filteredTotal,
  storeTotal,
  computed(() => catalogStore.entities.length)
)
const filteredEntities = computed(() => catalogStore.entities)
 
const catalogSortOptions = computed<SortOption[]>(() => [
  { value: 'name', label: t('common.name') },
  { value: 'createdAt', label: t('common.createdAt') }
])
 
function handleSortFieldChange(fieldId: string) {
  catalogStore.fetchCatalog(undefined, {
    fieldId: fieldId as CatalogSort['fieldId'],
    direction: 'asc'
  })
}
 
function handleSortDirectionToggle() {
  Iif (!catalogStore.sort) return
  catalogStore.fetchCatalog(undefined, {
    fieldId: catalogStore.sort.fieldId,
    direction: catalogStore.sort.direction === 'asc' ? 'desc' : 'asc'
  })
}
 
onMounted(async () => {
  await runSearchNow()
})
 
async function refreshCatalog() {
  searchQuery.value = appliedQuery.value
  await runSearchNow()
}
 
function displayEntityName(entity: Entity): string {
  Eif (typeof entity.name === 'string') return entity.name
  return entity.name?.en || entity.name?.fr || 'Unnamed Entity'
}
 
const forkModal = reactive<{
  open: boolean
  entity: Entity | null
  entityName: string
  defaultName: string
  loading: boolean
  error: string
}>({
  open: false,
  entity: null,
  entityName: '',
  defaultName: '',
  loading: false,
  error: ''
})
 
function handleFork(entity: Entity) {
  forkModal.entity = entity
  forkModal.entityName = displayEntityName(entity)
  forkModal.defaultName = `${displayEntityName(entity)} (Fork)`
  forkModal.error = ''
  forkModal.open = true
}
 
async function confirmFork({ name, copyItems }: { name: string; copyItems: boolean }) {
  const entity = forkModal.entity
  Iif (!entity) return
 
  forkModal.loading = true
  forkModal.error = ''
 
  try {
    const forkedEntity = await forkJob.run(entity.id, {
      name,
      visibility: 'flow-members',
      copyItems
    })
    // Polling was abandoned before the job settled — nothing to report.
    Iif (!forkedEntity) return
 
    forkModal.open = false
 
    // Mark as forked locally
    catalogStore.markAsForked(entity.id)
 
    toastStore.success(
      withRenamedFields(t('catalog.fork-success').replace('{name}', displayEntityName(entity)))
    )
    await router.push(flowLink('entity-items', { entityId: forkedEntity.id }))
  } catch (err: any) {
    forkModal.error = getErrorMessage(err, 'Failed to fork entity', t)
    toastStore.error(t('catalog.fork-error'))
  } finally {
    forkModal.loading = false
  }
}
 
async function handleLink(entity: Entity) {
  try {
    await entitiesStore.linkEntity(entity.id)
    catalogStore.markAsLinked(entity.id)
    toastStore.success(t('catalog.link-success').replace('{name}', displayEntityName(entity)))
  } catch {
    toastStore.error(t('catalog.link-error'))
  }
}
 
async function handleSubscribe(entity: Entity) {
  // Optimistic: flip the button immediately, roll it back if the request fails.
  catalogStore.markAsSubscribed(entity.id)
  try {
    await entitiesStore.subscribeToEntity(entity.id)
    toastStore.success(t('catalog.subscribe-success').replace('{name}', displayEntityName(entity)))
  } catch (err) {
    catalogStore.markAsUnsubscribed(entity.id)
    toastStore.error(getErrorMessage(err, t('catalog.subscribe-error')))
  }
}
 
async function handleUnsubscribe(entity: Entity) {
  catalogStore.markAsUnsubscribed(entity.id)
  try {
    await entitiesStore.unsubscribeFromEntity(entity.id)
    toastStore.success(
      t('catalog.unsubscribe-success').replace('{name}', displayEntityName(entity))
    )
  } catch (err) {
    catalogStore.markAsSubscribed(entity.id)
    toastStore.error(getErrorMessage(err, t('catalog.unsubscribe-error')))
  }
}
</script>
 
<style scoped>
/* 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%);
}
 
.input-group {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
 
.input-group .form-control:focus {
  box-shadow: none;
  border-color: #689909;
}
 
.input-group .input-group-text {
  border-color: #e9ecef;
}
 
/* Mobile optimization */
@media (max-width: 767px) {
  .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>