All files / src/components ExportEntitySidebar.vue

91.6% Statements 131/143
86.45% Branches 83/96
89.18% Functions 33/37
95.08% Lines 116/122

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  327x                           67x       3x                                 3x 3x                   3x     3x     2x             3x         3x 3x 3x                   3x 3x           3x                                           56x 3x               7x                                         3x                             1x       3x                                                                 161x 161x                             161x   169x       161x 161x 1x 1x   161x 6x             161x                                                   161x 161x 161x 161x 161x 161x 161x 161x         161x 49x 23x 49x   23x 49x 49x 41x 41x 41x     23x             161x 30x 16x 16x 16x     32x 32x 32x 30x 30x 16x 16x       30x 16x     16x       242x                 63x 37x       7x 7x 7x 6x   1x   7x       1x 1x     1x   1x       1x 1x                 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 16x 16x   9x     25x       161x 173x   173x 25x 25x         161x 194x       3x   3x 5x 2x   3x 1x 1x     2x 3x 1x 2x 3x     2x                 1x      
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    storage-key="export-entity-sidebar"
    :title="t('entity.exportModalTitle')"
    icon="fa-solid fa-file-export"
    panel-width="700px"
    :loading="loading"
    :submit-disabled="submitDisabled"
    :submit-label="t('entity.exportEntity')"
    submit-icon="fa-solid fa-file-export"
    submit-button-class="btn-primary"
    @close="handleClose"
    @submit="confirm"
  >
    <p class="text-muted">{{ t('entity.exportModalMessage').replace('{name}', entityName) }}</p>
    <div v-if="error" class="alert alert-danger" role="alert">{{ error }}</div>
 
    <div v-if="isJobInProgress" class="mb-3">
      <div class="d-flex justify-content-between small text-muted mb-1">
        <span>{{ jobProgressLabel }}</span>
        <span v-if="progressKnown">{{ progressPercent }}%</span>
      </div>
      <div class="progress" style="height: 0.5rem">
        <div
          class="progress-bar"
          :class="{ 'progress-bar-striped progress-bar-animated': !progressKnown }"
          role="progressbar"
          :style="{ width: `${progressKnown ? progressPercent : 100}%` }"
          :aria-valuenow="progress?.done ?? 0"
          aria-valuemin="0"
          :aria-valuemax="progress?.total ?? 1"
        />
      </div>
    </div>
 
    <div class="mb-3">
      <div class="form-check mb-2">
        <input
          id="export-format-json"
          v-model="format"
          class="form-check-input"
          type="radio"
          value="json"
        />
        <label class="form-check-label" for="export-format-json">
          <strong>{{ t('entity.exportFormatJsonLabel') }}</strong>
          <div class="text-muted small">{{ t('entity.exportFormatJsonHelp') }}</div>
        </label>
      </div>
      <div class="form-check">
        <input
          id="export-format-csv"
          v-model="format"
          class="form-check-input"
          type="radio"
          value="csv"
        />
        <label class="form-check-label" for="export-format-csv">
          <strong>{{ t('entity.exportFormatCsvLabel') }}</strong>
          <div class="text-muted small">{{ t('entity.exportFormatCsvHelp') }}</div>
        </label>
      </div>
    </div>
 
    <div class="mb-3">
      <label class="form-label small fw-bold">{{ t('entity.exportSectionDependencies') }}</label>
      <div class="text-muted small mb-2">{{ t('entity.exportDependenciesHelp') }}</div>
 
      <div v-if="discovering" class="text-muted small">
        <span class="spinner-border spinner-border-sm me-2" />
        {{ t('entity.exportDependenciesLoading') }}
      </div>
      <div v-else-if="discoverError" class="alert alert-danger py-2 px-3 small mb-0">
        {{ discoverError }}
      </div>
      <template v-else>
        <div class="table-responsive">
          <table class="table table-sm export-dependency-table align-middle mb-0">
            <thead>
              <tr>
                <th scope="col" class="text-center" style="width: 2.5rem">
                  {{ t('entity.exportTableHeaderInclude') }}
                </th>
                <th scope="col">{{ t('entity.exportTableHeaderEntity') }}</th>
                <template v-if="format === 'json'">
                  <th
                    scope="col"
                    class="text-center"
                    style="width: 4rem"
                    :title="t('entity.exportIncludeItemsHelp')"
                  >
                    {{ t('entity.exportIncludeItemsLabel') }}
                  </th>
                  <th
                    scope="col"
                    class="text-center"
                    style="width: 4rem"
                    :title="t('entity.exportIncludeImagesHelp')"
                  >
                    {{ t('entity.exportIncludeImagesLabel') }}
                  </th>
                </template>
              </tr>
            </thead>
            <tbody>
              <tr v-for="node in tree" :key="node.key" class="export-dependency-row">
                <td class="text-center">
                  <input
                    class="form-check-input"
                    type="checkbox"
                    :checked="isChecked(node.row)"
                    :disabled="!canToggle(node.row)"
                    :aria-label="node.row.name"
                    name="export-entity"
                    @change="toggleRow(node.row)"
                  />
                </td>
                <td :style="{ paddingLeft: `${node.depth * 1.25 + 0.5}rem` }">
                  <span :class="{ 'text-muted': !isChecked(node.row) }">{{ node.row.name }}</span>
                  <span v-if="node.row.isRoot" class="badge bg-secondary ms-2">
                    {{ t('entity.exportDependencyRootBadge') }}
                  </span>
                  <span v-else-if="node.repeated" class="text-muted small ms-2">
                    {{ t('entity.exportDependencyAlsoAbove') }}
                  </span>
                  <div
                    v-if="
                      !isChecked(node.row) && !node.row.isRoot && !excludedByUser.has(node.row.id)
                    "
                    class="text-muted small"
                  >
                    {{ t('entity.exportDependencyExcludedHint') }}
                  </div>
                </td>
                <template v-if="format === 'json'">
                  <td class="text-center">
                    <input
                      v-if="node.row.itemCount > 0"
                      class="form-check-input"
                      type="checkbox"
                      :checked="!itemsExcluded.has(node.row.id)"
                      :disabled="!isChecked(node.row)"
                      :aria-label="t('entity.exportIncludeItemsLabel')"
                      :title="
                        t('entity.exportDependencyItemCount').replace(
                          '{count}',
                          String(node.row.itemCount)
                        )
                      "
                      name="export-items"
                      @change="toggleItems(node.row)"
                    />
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td class="text-center">
                    <input
                      v-if="node.row.hasImages"
                      class="form-check-input"
                      type="checkbox"
                      :checked="!imagesExcluded.has(node.row.id)"
                      :disabled="!isChecked(node.row)"
                      :aria-label="t('entity.exportIncludeImagesLabel')"
                      name="export-images"
                      @change="toggleImages(node.row)"
                    />
                    <span v-else class="text-muted">—</span>
                  </td>
                </template>
              </tr>
            </tbody>
          </table>
        </div>
 
        <div v-if="cyclesBroken.length > 0" class="alert alert-warning py-2 px-3 small mt-2 mb-0">
          {{ t('entity.exportCyclesWarning') }}
        </div>
      </template>
    </div>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useEntitiesStore, type ExportDiscoveredEntity } from '@/stores/entities'
 
const { t } = useUILanguage()
const entitiesStore = useEntitiesStore()
 
interface Props {
  isOpen: boolean
  entityId: string | null
  entityName: string
  loading?: boolean
  error?: string
  // Job status/progress while the export job started by `confirm` is
  // pending/processing on the server — undefined before submit and once
  // the job settles, since `loading` alone can't tell the two apart.
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: { done: number; total: number } | null
}
 
const props = defineProps<Props>()
 
const isJobInProgress = computed(() => props.status === 'pending' || props.status === 'processing')
// `total` is only known once the worker has finished discovery — until then
// `progress` is `{ done: 0, total: null }`, not absent, so it can't be used
// on its own to tell "no progress yet" from "progress known".
const progressKnown = computed(() => !!props.progress && props.progress.total != null)
const progressPercent = computed(() => {
  Iif (!progressKnown.value || props.progress!.total <= 0) return 0
  return Math.min(100, Math.round((props.progress!.done / props.progress!.total) * 100))
})
const jobProgressLabel = computed(() =>
  progressKnown.value
    ? t('entity.exportProgress')
        .replace('{done}', String(props.progress!.done))
        .replace('{total}', String(props.progress!.total))
    : t('entity.exportPreparing')
)
 
const emit = defineEmits<{
  confirm: [
    payload: {
      format: 'json' | 'csv'
      excludeEntityIds?: string[]
      excludeItemsEntityIds?: string[]
      excludeImagesEntityIds?: string[]
    }
  ]
  cancel: []
}>()
 
interface TreeNode {
  key: string
  row: ExportDiscoveredEntity
  depth: number
  // True when this same entity already appears higher up the tree (a
  // dependency shared by more than one parent) — shown again here for a
  // faithful tree view, but its checkbox state is the same underlying row.
  repeated: boolean
}
 
// The container is always a zip; this only picks what goes inside it — a
// re-importable JSON bundle (schema + items, images/items still toggleable
// per row), or one items-only CSV per included entity (no schema, no
// images, so the per-row items/images toggles don't apply and are hidden).
const format = ref<'json' | 'csv'>('json')
const rows = ref<ExportDiscoveredEntity[]>([])
const excludedByUser = ref<Set<string>>(new Set())
const itemsExcluded = ref<Set<string>>(new Set())
const imagesExcluded = ref<Set<string>>(new Set())
const discovering = ref(false)
const discoverError = ref('')
const cyclesBroken = ref<string[]>([])
 
// Reachability from the root(s), following `dependsOn` edges but never
// entering a node the user excluded — so any entity only reachable through
// an excluded one falls out of the checked set automatically (cascade).
const reachableIds = computed(() => {
  const byId = new Map(rows.value.map((row) => [row.id, row]))
  const reachable = new Set<string>()
  const queue = rows.value.filter((row) => row.isRoot).map((row) => row.id)
 
  while (queue.length > 0) {
    const id = queue.shift()!
    if (reachable.has(id) || excludedByUser.value.has(id)) continue
    reachable.add(id)
    const row = byId.get(id)
    Eif (row) queue.push(...row.dependsOn)
  }
 
  return reachable
})
 
// Depth-first tree view built from the flat `dependsOn` edges, starting at
// the root(s). A dependency shared by more than one parent is rendered
// again under each parent (marked `repeated`) rather than collapsed, so the
// tree always reflects the real reference structure.
const tree = computed<TreeNode[]>(() => {
  const byId = new Map(rows.value.map((row) => [row.id, row]))
  const result: TreeNode[] = []
  const seen = new Set<string>()
  let counter = 0
 
  function visit(row: ExportDiscoveredEntity, depth: number) {
    const repeated = seen.has(row.id)
    result.push({ key: `${row.id}:${counter++}`, row, depth, repeated })
    if (repeated) return
    seen.add(row.id)
    for (const depId of row.dependsOn) {
      const depRow = byId.get(depId)
      Eif (depRow) visit(depRow, depth + 1)
    }
  }
 
  for (const row of rows.value.filter((r) => r.isRoot)) {
    visit(row, 0)
  }
 
  return result
})
 
function isChecked(row: ExportDiscoveredEntity): boolean {
  return reachableIds.value.has(row.id)
}
 
// A row can only be toggled when doing so has an effect: it's currently
// reachable (unchecking removes it), or the user directly excluded it
// (re-checking restores it). A row orphaned only by cascade (some other,
// excluded entity was its sole path in) has nothing to toggle until that
// blocking ancestor is re-included.
function canToggle(row: ExportDiscoveredEntity): boolean {
  if (row.isRoot) return false
  return isChecked(row) || excludedByUser.value.has(row.id)
}
 
function toggleRow(row: ExportDiscoveredEntity) {
  Iif (!canToggle(row)) return
  const next = new Set(excludedByUser.value)
  if (isChecked(row)) {
    next.add(row.id)
  } else {
    next.delete(row.id)
  }
  excludedByUser.value = next
}
 
function toggleSetMember(set: Set<string>, id: string): Set<string> {
  const next = new Set(set)
  Iif (next.has(id)) {
    next.delete(id)
  } else {
    next.add(id)
  }
  return next
}
 
function toggleItems(row: ExportDiscoveredEntity) {
  Iif (!isChecked(row)) return
  itemsExcluded.value = toggleSetMember(itemsExcluded.value, row.id)
}
 
function toggleImages(row: ExportDiscoveredEntity) {
  if (!isChecked(row)) return
  imagesExcluded.value = toggleSetMember(imagesExcluded.value, row.id)
}
 
async function loadDependencies() {
  Iif (!props.entityId) return
 
  rows.value = []
  excludedByUser.value = new Set()
  itemsExcluded.value = new Set()
  imagesExcluded.value = new Set()
  cyclesBroken.value = []
  discoverError.value = ''
  discovering.value = true
  try {
    const result = await entitiesStore.discoverExportBundle([props.entityId])
    rows.value = result.entities
    cyclesBroken.value = result.cyclesBroken
  } catch (err: any) {
    discoverError.value =
      err.response?.data?.error || err.message || t('entity.exportDiscoverError')
  } finally {
    discovering.value = false
  }
}
 
watch(
  () => props.isOpen,
  (open) => {
    if (!open) return
    format.value = 'json'
    loadDependencies()
  },
  { immediate: true }
)
 
const submitDisabled = computed(
  () => discovering.value || !!discoverError.value || isJobInProgress.value
)
 
function confirm() {
  Iif (props.loading || submitDisabled.value) return
 
  const excludeEntityIds = rows.value
    .filter((row) => !row.isRoot && !isChecked(row))
    .map((row) => row.id)
 
  if (format.value === 'csv') {
    emit('confirm', { format: 'csv', excludeEntityIds })
    return
  }
 
  const excludeItemsEntityIds = rows.value
    .filter((row) => isChecked(row) && itemsExcluded.value.has(row.id))
    .map((row) => row.id)
  const excludeImagesEntityIds = rows.value
    .filter((row) => isChecked(row) && imagesExcluded.value.has(row.id))
    .map((row) => row.id)
 
  emit('confirm', {
    format: 'json',
    excludeEntityIds,
    excludeItemsEntityIds,
    excludeImagesEntityIds
  })
}
 
function handleClose() {
  Eif (!props.loading) emit('cancel')
}
</script>