All files / src/views EntitiesPage.vue

75.52% Statements 179/237
76.81% Branches 106/138
71.69% Functions 38/53
76.23% Lines 170/223

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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798      83x           1x                     1x                 1x                                 1x                                           83x                                               46x         1x 1x                         5x         40x                       6x                                                                                                                                                                                                                                     48x 48x   48x 4x     48x 48x 48x 48x 48x 48x   48x 48x     48x             48x       48x           48x 48x 43x     48x     46x     48x   48x                 2x       1x       1x 1x             48x       17x 2x   16x           48x   48x                                       48x 48x 48x 48x 48x 48x 43x         1x           7x 7x 7x                   7x 7x       9x 9x                   9x 9x       13x 13x 13x   13x   13x   13x     13x             13x 1x 1x 1x         12x 12x             12x       12x 1x 1x 1x     11x                             13x 8x 8x   3x 3x 1x         2x           2x   3x   13x       48x                                 7x 7x 7x 7x 7x       6x 6x   6x 6x   6x 6x           4x 4x 4x   2x 2x   6x       48x                                   48x                 48x 1x   48x 6x       5x 5x 5x 5x       1x 1x                 4x 4x   4x 4x 4x 4x   4x 4x 3x   3x 1x 1x 1x 2x 1x 1x         1x 1x   4x       48x 48x   48x                                       48x   48x     48x 4x                                                                               2x 2x 2x 2x   2x 2x 2x   2x 1x 1x 1x 1x 1x               2x                                                 2x 2x 2x 1x       1x 1x         1x 1x 1x 1x                                                                                                  
<template>
  <PageLayout :title="t('navigation.entities')" class="entities-page">
    <template #action>
      <!-- Label always shown: the page holds several edit actions, an icon alone would be ambiguous -->
      <button
        v-if="authStore.currentFlow && canManageFlow"
        type="button"
        class="btn btn-outline-primary me-2"
        data-testid="edit-flow-btn"
        @click="openFlowEdit(authStore.currentFlow)"
      >
        <font-awesome-icon icon="fa-solid fa-sliders" class="me-2" />
        <span>{{ t('flow.editFlow') }}</span>
      </button>
      <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('entities:create')"
        class="btn btn-outline-secondary me-2"
        data-tour="entities-import"
        @click="triggerImportFilePicker"
      >
        <font-awesome-icon icon="fa-solid fa-file-import" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('entity.import') }}</span>
      </button>
      <input
        ref="importFileInputRef"
        type="file"
        accept="application/zip,.zip"
        class="d-none"
        name="import-file"
        @change="handleImportFileSelected"
      />
      <button
        v-if="authStore.currentFlow && hasPermission('entities:create')"
        class="btn btn-success"
        data-tour="entities-create"
        @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"
      mode="create"
      :form-data="newEntity"
      :entity-id="newEntityId"
      :default-language="defaultLanguage"
      :enabled-languages="enabledLanguages"
      :current-language="currentFormLanguage"
      :loading="formLoading"
      :error="formError"
      :name-error="nameError(newEntity.name)"
      :field-errors="fieldDefinitionErrors"
      :has-items="false"
      :links-info="null"
      @update:form-data="newEntity = $event"
      @update:current-language="currentFormLanguage = $event"
      @close="cancelCreate"
      @submit="handleCreateEntity"
    />
 
    <EntityEditSidebar ref="entityEditSidebar" />
 
    <div v-if="!authStore.currentFlow" class="container-fluid">
      <NoActiveFlowNotice />
    </div>
 
    <div v-if="authStore.currentFlow" class="container-fluid">
      <SearchFilterHeader
        v-if="!isPermissionDenied"
        v-model="searchQuery"
        :placeholder="t('entity.searchPlaceholder')"
        :filtered-count="filteredCount"
        :total-count="totalCount"
      >
        <template #extra>
          <SortControl
            :options="entitySortOptions"
            :field-value="entitiesStore.sort?.fieldId || DEFAULT_ENTITY_SORT.fieldId"
            :direction="entitiesStore.sort?.direction || 'asc'"
            :label="t('common.sortBy')"
            @update:field-value="handleSortFieldChange"
            @toggle-direction="handleSortDirectionToggle"
          />
        </template>
      </SearchFilterHeader>
 
      <div v-if="importParseError" class="row mb-3">
        <div class="col-12">
          <div class="alert alert-danger mb-0 d-flex justify-content-between align-items-center">
            <span>{{ importParseError }}</span>
            <button
              type="button"
              class="btn-close"
              :aria-label="t('common.close')"
              @click="importParseError = ''"
            ></button>
          </div>
        </div>
      </div>
 
      <EmptyState v-if="isPermissionDenied" variant="info">
        {{ t('entity.noListPermission') }}
      </EmptyState>
      <ErrorAlert v-else-if="storeError" :title="t('common.accessDenied')" :message="storeError" />
      <LoadingSpinner v-else-if="loading" />
      <EmptyState v-else-if="filteredCount === 0" variant="info">
        {{ searchQuery ? t('common.noResults') : t('entity.noEntities') }}
      </EmptyState>
    </div>
 
    <!-- Entity Cards Grid -->
    <VirtualCardGrid
      v-if="authStore.currentFlow && !isPermissionDenied && !loading && filteredCount > 0"
      :items="filteredEntities"
      :has-more="entitiesStore.hasMore"
      :is-loading="loading"
      @load-more="entitiesStore.loadMore()"
    >
      <template #card="{ item: entity }">
        <EntityCard
          :entity="entity"
          @edit="entityEditSidebar?.startEdit($event)"
          @inspect="entityEditSidebar?.startInspect($event)"
          @export="handleExportEntity"
          @fork="handleForkEntity"
          @unlink="handleUnlinkEntity"
          @subscribe="handleSubscribeEntity"
          @unsubscribe="handleUnsubscribeEntity"
        />
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <!-- Fork entity confirmation (optionally copy items) -->
  <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="confirmForkEntity"
    @cancel="forkModal.open = false"
  />
 
  <!-- Export entity: ZIP (schema + items + images + private dependencies, all
       individually toggleable) or CSV (items only) -->
  <ExportEntitySidebar
    :is-open="exportModal.open"
    :entity-id="exportModal.entity?.id ?? null"
    :entity-name="exportModal.entityName"
    :loading="exportModal.loading"
    :error="exportModal.error"
    :status="exportModal.status"
    :progress="exportModal.progress"
    @confirm="confirmExportEntity"
    @cancel="cancelExportEntity"
  />
 
  <!-- Import preview: review every entity in the bundle (the one exported plus
       any bundled dependencies), choose merge/create/skip per entity, then
       commit them all at once. -->
  <ImportPreviewSidebar
    :is-open="importPreview.open"
    :bundle="importPreview.bundle"
    :check-results="importPreview.checkResults"
    :loading="importPreview.loading"
    :error="importPreview.error"
    :results="importPreview.results"
    :status="importPreview.status"
    :progress="importPreview.progress"
    @confirm="confirmImportPreview"
    @cancel="cancelImportPreview"
    @close="closeImportPreview"
  />
 
  <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.2, UC-ENTITY-008.1, UC-ENTITY-009.1, UC-ENTITY-018.1, UC-ENTITY-019.1, UC-ENTITY-020.1, UC-ENTITY-023.1, UC-RBAC-007.1, UC-RBAC-008.1, UC-CATALOG-005.1, UC-ENTITY-026.2, UC-FLOW-009.1
import { ref, onMounted, reactive, computed, watch } 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 EntityEditSidebar from '@/components/EntityEditSidebar.vue'
import ForkEntityModal from '@/components/ForkEntityModal.vue'
import ExportEntitySidebar from '@/components/ExportEntitySidebar.vue'
import ImportPreviewSidebar from '@/components/ImportPreviewSidebar.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 NoActiveFlowNotice from '@/components/NoActiveFlowNotice.vue'
import ErrorAlert from '@/components/ErrorAlert.vue'
import {
  useEntitiesStore,
  DEFAULT_ENTITY_SORT,
  type EntityField,
  type EntitySort,
  type ImportCheckResult,
  type ImportBundleEntry,
  type ImportBundleResult
} from '@/stores/entities'
import { useAuthStore } from '@/stores/auth'
import { useFlowEditSidebar } from '@/composables/useFlowEditSidebar'
import { useEntityFormErrors } from '@/composables/useEntityFormErrors'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { usePermissions } from '@/composables/usePermissions'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
import { useFilteredCounts } from '@/composables/useFilteredCounts'
import { storeToRefs } from 'pinia'
import { isReservedEntityName, type VisibilityLevel } from '@/utils/constants'
import {
  validateEntityFields,
  ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY,
  type FieldErrorMap
} from '@/utils/entityValidation'
import { parseEntityBundleZip, type EntityExportBundle } from '@/utils/entityExportBundle'
import { stageImportImages } from '@/utils/entityImportStaging'
import { useToastStore } from '@/stores/toast'
import { usePollUntilComplete } from '@/composables/usePollUntilComplete'
import { useForkJob } from '@/composables/useForkJob'
import { renamedFieldsText } from '@/utils/renamedFields'
import { getErrorMessage } from '@/utils/errors'
import { cleanEmailTemplates } from '@/utils/emailTemplates'
import type { EmailTemplate } from '@/schemas/entity-schema'
 
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 authStore = useAuthStore()
const toastStore = useToastStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
const { hasPermission } = usePermissions()
const { openFlowEdit } = useFlowEditSidebar()
const { fieldErrorMessage, emailTemplateErrorText, emailTemplatesError, nameError } =
  useEntityFormErrors()
const entityEditSidebar = ref<InstanceType<typeof EntityEditSidebar> | null>(null)
// Same gate as the menu's "Flow settings": the flow edit sidebar holds both
// the settings update and the Danger Zone delete
const canManageFlow = computed(() => hasPermission('flows:update') || hasPermission('flows:delete'))
const {
  loading,
  error: storeError,
  errorStatus: storeErrorStatus,
  filteredTotal,
  total: storeTotal
} = storeToRefs(entitiesStore)
 
// Listing may be denied while creating is still allowed — skip the fetch to
// avoid a guaranteed 403 and show a neutral message instead of an error.
const canListEntities = computed(() => hasPermission('entities:list'))
 
// The client-side permission check can momentarily disagree with the backend's
// (e.g. right after a role change). Treat a 403 from the list fetch the same as
// "no permission" — the friendly noListPermission message — rather than surfacing
// the raw backend error in the generic Access Denied box.
const isPermissionDenied = computed(() => !canListEntities.value || storeErrorStatus.value === 403)
const { searchQuery, appliedQuery, runSearchNow } = useDebouncedSearch(async (query) => {
  await entitiesStore.fetchEntities(true, query)
})
 
const { filteredCount, totalCount } = useFilteredCounts(
  filteredTotal,
  storeTotal,
  computed(() => entitiesStore.entities.length)
)
 
const filteredEntities = computed(() => entitiesStore.entities)
 
const entitySortOptions = computed<SortOption[]>(() => [
  { value: 'name', label: t('common.name') },
  { value: 'createdAt', label: t('common.createdAt') }
])
 
// Mirrors refreshEntities/runSearchNow: fetchEntities already records any
// failure on the store's own `error` ref (rendered via ErrorAlert above), so
// no separate try/catch is needed here.
async function applyEntitySort(newSort: EntitySort) {
  await entitiesStore.fetchEntities(true, undefined, newSort)
}
 
function handleSortFieldChange(fieldId: string) {
  applyEntitySort({ fieldId: fieldId as EntitySort['fieldId'], direction: 'asc' })
}
 
function handleSortDirectionToggle() {
  Iif (!entitiesStore.sort) return
  applyEntitySort({
    fieldId: entitiesStore.sort.fieldId,
    direction: entitiesStore.sort.direction === 'asc' ? 'desc' : 'asc'
  })
}
 
// 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))
}
 
// Generated up front so picture/icon uploads during creation are keyed by
// the entity's real, final id from the start — sent to the API as `id` on
// create — instead of a placeholder that would need reconciling afterward.
const newEntityId = ref(crypto.randomUUID())
 
const newEntity = ref<{
  name: string | Record<string, string>
  description?: string | Record<string, string>
  visibility: VisibilityLevel
  commentsEnabled?: boolean
  fields: EntityField[]
  forms?: any[]
  emailTemplates?: EmailTemplate[]
  picture?: string
  icon?: string
}>({
  name: { en: '', fr: '' },
  description: undefined,
  visibility: 'flow-members',
  commentsEnabled: false,
  fields: [],
  forms: [],
  picture: undefined,
  icon: undefined
})
const isCreating = ref(false)
const formLoading = ref(false)
const formError = ref('')
const fieldDefinitionErrors = ref<FieldErrorMap>({})
onMounted(async () => {
  if (authStore.currentFlow && canListEntities.value) {
    await runSearchNow()
  }
})
 
async function refreshEntities() {
  Eif (!canListEntities.value) return
  searchQuery.value = appliedQuery.value
  await runSearchNow()
}
 
function startCreate() {
  isCreating.value = true
  newEntityId.value = crypto.randomUUID()
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    commentsEnabled: false,
    fields: [],
    forms: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
  fieldDefinitionErrors.value = {}
}
 
function cancelCreate() {
  isCreating.value = false
  newEntity.value = {
    name: { en: '', fr: '' },
    description: undefined,
    visibility: 'flow-members',
    commentsEnabled: false,
    fields: [],
    forms: [],
    picture: undefined,
    icon: undefined
  }
  formError.value = ''
  fieldDefinitionErrors.value = {}
}
 
async function handleCreateEntity() {
  formLoading.value = true
  formError.value = ''
  fieldDefinitionErrors.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 = t('entity.nameRequired')
      formLoading.value = false
      return
    }
 
    // Validate entity name is not reserved
    if (isNameReserved(newEntity.value.name)) {
      formError.value = nameError(newEntity.value.name) || t('entity.nameRequired')
      formLoading.value = false
      return
    }
 
    // Validate field definitions: known type, well-formed select options,
    // sound number min/max/step, positive length/maxLines
    const definitionErrors = validateEntityFields(newEntity.value.fields)
    Iif (Object.keys(definitionErrors).length > 0) {
      fieldDefinitionErrors.value = definitionErrors
      formError.value = t('entity.fixFieldErrors')
      formLoading.value = false
      return
    }
 
    const templateError = emailTemplatesError(
      newEntity.value.emailTemplates,
      newEntity.value.fields
    )
    if (templateError) {
      formError.value = templateError
      formLoading.value = false
      return
    }
 
    const payload = {
      id: newEntityId.value,
      name: newEntity.value.name,
      fields: newEntity.value.fields,
      visibility: newEntity.value.visibility,
      commentsEnabled: newEntity.value.commentsEnabled ?? false,
      ...(newEntity.value.description && { description: newEntity.value.description }),
      ...(newEntity.value.forms?.length && { forms: newEntity.value.forms }),
      ...(newEntity.value.emailTemplates?.length && {
        emailTemplates: cleanEmailTemplates(newEntity.value.emailTemplates)
      }),
      ...(newEntity.value.picture && { picture: newEntity.value.picture }),
      ...(newEntity.value.icon && { icon: newEntity.value.icon })
    }
 
    await entitiesStore.createEntity(payload)
    cancelCreate()
    toastStore.success(t('entity.createSuccess'))
  } catch (err: any) {
    const errData = err.response?.data
    if (errData?.error === 'INVALID_EMAIL_TEMPLATE') {
      formError.value = emailTemplateErrorText(
        errData,
        newEntity.value.emailTemplates,
        newEntity.value.fields
      )
    } else Iif (ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY[errData?.error] && errData?.fieldId) {
      fieldDefinitionErrors.value = {
        [errData.fieldId]: ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY[errData.error]
      }
      formError.value = fieldErrorMessage(errData, newEntity.value.fields ?? [])
    } else {
      formError.value = getErrorMessage(err, 'Failed to create entity', t)
    }
    toastStore.error(t('entity.createError'))
  } finally {
    formLoading.value = false
  }
}
 
const forkModal = reactive<{
  open: boolean
  entity: any
  entityName: string
  defaultName: string
  loading: boolean
  error: string
}>({
  open: false,
  entity: null,
  entityName: '',
  defaultName: '',
  loading: false,
  error: ''
})
 
function handleForkEntity(entity: any) {
  forkModal.entity = entity
  forkModal.entityName = getTranslation(entity.name)
  forkModal.defaultName = `${getTranslation(entity.name)} (Fork)`
  forkModal.error = ''
  forkModal.open = true
}
 
async function confirmForkEntity({ 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
    toastStore.success(withRenamedFields(t('catalog.fork-success').replace('{name}', name)))
  } catch (err: any) {
    forkModal.error = getErrorMessage(err, 'Failed to fork entity', t)
    toastStore.error(t('catalog.fork-error'))
  } finally {
    forkModal.loading = false
  }
}
 
const exportModal = reactive<{
  open: boolean
  entity: any
  entityName: string
  loading: boolean
  error: string
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress: { done: number; total: number } | null
}>({
  open: false,
  entity: null,
  entityName: '',
  loading: false,
  error: '',
  status: undefined,
  progress: null
})
 
const exportJobPoll = usePollUntilComplete<{
  downloadUrl: string
  entityCount: number
  cyclesBroken: string[]
}>()
 
// Mirrored into exportModal (rather than binding exportJobPoll's refs
// directly) so the sidebar's props stay grouped with the rest of the
// modal's state, same as loading/error/open above.
watch(exportJobPoll.progress, (progress) => {
  exportModal.progress = progress
})
watch(exportJobPoll.status, (status) => {
  exportModal.status = status === 'idle' ? undefined : status
})
 
function handleExportEntity(entity: any) {
  exportModal.entity = entity
  exportModal.entityName = getTranslation(entity.name)
  exportModal.error = ''
  exportModal.open = true
}
 
function cancelExportEntity() {
  exportJobPoll.stop()
  exportModal.open = false
}
 
async function confirmExportEntity(payload: {
  format: 'json' | 'csv'
  excludeEntityIds?: string[]
  excludeItemsEntityIds?: string[]
  excludeImagesEntityIds?: string[]
}) {
  const entity = exportModal.entity
  Iif (!entity) return
 
  exportModal.loading = true
  exportModal.error = ''
  exportModal.status = undefined
  exportModal.progress = null
 
  try {
    const { jobId } = await entitiesStore.exportEntities([entity.id], payload)
    await exportJobPoll.start(() => entitiesStore.getExportJobStatus(jobId))
 
    if (exportJobPoll.status.value === 'completed' && exportJobPoll.result.value) {
      window.location.href = exportJobPoll.result.value.downloadUrl
      exportModal.open = false
      toastStore.success(t('entity.exportSuccess'))
    } else if (exportJobPoll.status.value === 'failed') {
      exportModal.error = exportJobPoll.error.value || 'Failed to export entity'
      toastStore.error(t('entity.exportError'))
    }
    // Any other status means polling was stopped early (the sidebar was
    // closed before the job settled) — nothing left to report.
  } catch (err: any) {
    exportModal.error = getErrorMessage(err, 'Failed to export entity')
    toastStore.error(t('entity.exportError'))
  } finally {
    exportModal.loading = false
  }
}
 
const importFileInputRef = ref<HTMLInputElement | null>(null)
const importParseError = ref('')
 
const importPreview = reactive<{
  open: boolean
  bundle: EntityExportBundle | null
  checkResults: ImportCheckResult[]
  loading: boolean
  error: string
  results: ImportBundleResult[] | null
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress: { done: number; total: number } | null
}>({
  open: false,
  bundle: null,
  checkResults: [],
  loading: false,
  error: '',
  results: null,
  status: undefined,
  progress: null
})
 
const importJobPoll = usePollUntilComplete<{ results: ImportBundleResult[] }>()
 
watch(importJobPoll.progress, (progress) => {
  importPreview.progress = progress
})
watch(importJobPoll.status, (status) => {
  importPreview.status = status === 'idle' ? undefined : status
})
 
function cancelImportPreview() {
  importJobPoll.stop()
  importPreview.open = false
}
 
function triggerImportFilePicker() {
  importParseError.value = ''
  importFileInputRef.value?.click()
}
 
async function handleImportFileSelected(event: Event) {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  // Reset so selecting the same file again still fires a change event
  input.value = ''
  if (!file) return
 
  importParseError.value = ''
  try {
    const { bundle, imageBlobs } = await parseEntityBundleZip(file)
    const stagedBundle = await stageImportImages(bundle, imageBlobs)
 
    const checkResults = await entitiesStore.checkImportBundle(
      stagedBundle.entities.map((entry) => ({ tempId: entry.tempId, entity: entry.entity }))
    )
 
    importPreview.bundle = stagedBundle
    importPreview.checkResults = checkResults
    importPreview.results = null
    importPreview.error = ''
    importPreview.open = true
  } catch (err: any) {
    importParseError.value = getErrorMessage(err, 'Failed to read import file')
  }
}
 
async function confirmImportPreview(entries: ImportBundleEntry[]) {
  importPreview.loading = true
  importPreview.error = ''
  importPreview.status = undefined
  importPreview.progress = null
 
  try {
    const { jobId } = await entitiesStore.importBundle(entries)
    await importJobPoll.start(() => entitiesStore.getImportJobStatus(jobId))
 
    if (importJobPoll.status.value === 'completed' && importJobPoll.result.value) {
      importPreview.results = importJobPoll.result.value.results
      toastStore.success(t('entity.importSuccess'))
    } else Eif (importJobPoll.status.value === 'failed') {
      importPreview.error = importJobPoll.error.value || 'Failed to import entities'
      toastStore.error(t('entity.importError'))
    }
    // Any other status means polling was stopped early (the sidebar was
    // closed before the job settled) — nothing left to report.
  } catch (err: any) {
    importPreview.error = getErrorMessage(err, 'Failed to import entities', t)
    toastStore.error(t('entity.importError'))
  } finally {
    importPreview.loading = false
  }
}
 
async function closeImportPreview() {
  importPreview.open = false
  importPreview.bundle = null
  importPreview.results = null
  // Some entities may have been created/merged even if others failed —
  // refresh the list to reflect whatever actually committed.
  await refreshEntities()
}
 
async function handleUnlinkEntity(entity: any) {
  try {
    await entitiesStore.unlinkEntity(entity.id)
    toastStore.success(t('catalog.unlink-success'))
  } catch (err: any) {
    formError.value = getErrorMessage(err, 'Failed to unlink entity')
    toastStore.error(t('catalog.unlink-error'))
  }
}
 
async function handleSubscribeEntity(entity: any) {
  // Optimistic: flip the button immediately, roll it back if the request fails.
  entitiesStore.markAsSubscribed(entity.id)
  try {
    await entitiesStore.subscribeToEntity(entity.id)
    toastStore.success(
      t('catalog.subscribe-success').replace('{name}', getTranslation(entity.name))
    )
  } catch (err: any) {
    entitiesStore.markAsUnsubscribed(entity.id)
    toastStore.error(getErrorMessage(err, t('catalog.subscribe-error')))
  }
}
 
async function handleUnsubscribeEntity(entity: any) {
  entitiesStore.markAsUnsubscribed(entity.id)
  try {
    await entitiesStore.unsubscribeFromEntity(entity.id)
    toastStore.success(
      t('catalog.unsubscribe-success').replace('{name}', getTranslation(entity.name))
    )
  } catch (err: any) {
    entitiesStore.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%);
}
 
/* 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>