All files / src/components ImportPreviewSidebar.vue

91.48% Statements 86/94
89.55% Branches 120/134
92.68% Functions 38/41
96.15% Lines 75/78

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  88x                                 10x                                                                                                                       2x                 32x             4x                                                         46x 4x 4x                                                                                                                   1x                 4x                                                                 3x                           1x                                   5x                                         77x 77x             2x 2x                                           77x   77x 77x 1x 1x   77x 2x             77x                                   77x     28x   28x 73x 50x 50x   50x 50x 50x 2x 48x 4x       4x 2x       50x                             92x         77x 78x   78x 28x                             4x     116x       76x 76x       40x 40x 40x   40x       118x 80x   80x 80x 76x   80x 40x   80x     77x 46x     81x     163x       1x   1x 3x 2x                     1x               2x 2x 1x   1x         1x      
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    storage-key="import-preview-sidebar"
    :title="title ?? t('entity.importPreviewTitle')"
    icon="fa-solid fa-file-import"
    panel-width="800px"
    :loading="loading"
    :submit-disabled="!canConfirm"
    :submit-label="submitLabel ?? t('entity.import')"
    submit-icon="fa-solid fa-file-import"
    submit-button-class="btn-primary"
    @close="handleClose"
    @submit="confirm"
  >
    <!-- Post-import summary -->
    <template v-if="results">
      <ul class="list-unstyled mb-0">
        <li v-for="row in rows" :key="row.tempId" class="mb-2">
          <span
            class="badge me-2"
            :class="{
              'bg-success': resultFor(row.tempId)?.status === 'created',
              'bg-info': resultFor(row.tempId)?.status === 'merged',
              'bg-secondary': resultFor(row.tempId)?.status === 'skipped',
              'bg-danger': resultFor(row.tempId)?.status === 'failed'
            }"
          >
            {{ t(`entity.importResultStatus.${resultFor(row.tempId)?.status}`) }}
          </span>
          <strong>{{ row.name }}</strong>
          <span v-if="resultFor(row.tempId)?.status === 'failed'" class="text-danger small">
            — {{ resultFor(row.tempId)?.error }}
          </span>
          <span v-else class="text-muted small">
            —
            {{
              t('entity.importResultItemsCount').replace(
                '{count}',
                String(resultFor(row.tempId)?.importedItemsCount ?? 0)
              )
            }}
            <template v-if="(resultFor(row.tempId)?.droppedFieldsCount ?? 0) > 0">
              ·
              {{
                t('entity.importResultDroppedFields').replace(
                  '{count}',
                  String(resultFor(row.tempId)?.droppedFieldsCount)
                )
              }}
            </template>
            <template v-if="(resultFor(row.tempId)?.renamedFields?.length ?? 0) > 0">
              ·
              {{ renamedFieldsText(t, resultFor(row.tempId)?.renamedFields ?? []) }}
            </template>
            <template v-if="(resultFor(row.tempId)?.unresolvedReferenceCount ?? 0) > 0">
              ·
              {{
                t('entity.importResultUnresolvedReferences').replace(
                  '{count}',
                  String(resultFor(row.tempId)?.unresolvedReferenceCount)
                )
              }}
            </template>
            <template v-if="(resultFor(row.tempId)?.invalidItemsCount ?? 0) > 0">
              ·
              {{
                t('entity.importResultInvalidItems').replace(
                  '{count}',
                  String(resultFor(row.tempId)?.invalidItemsCount)
                )
              }}
            </template>
          </span>
          <ul
            v-if="(resultFor(row.tempId)?.itemIssues?.length ?? 0) > 0"
            class="text-muted small mb-0 mt-1 ps-4"
          >
            <li v-for="(issue, index) in resultFor(row.tempId)?.itemIssues" :key="index">
              {{
                t('entity.importResultItemIssue').replace('{index}', String(issue.itemIndex + 1))
              }}
              — {{ itemIssueMessage(issue) }}
            </li>
          </ul>
        </li>
      </ul>
    </template>
 
    <!-- Editable preview -->
    <template v-else>
      <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="progress">{{ progressPercent }}%</span>
        </div>
        <div class="progress" style="height: 0.5rem">
          <div
            class="progress-bar"
            :class="{ 'progress-bar-striped progress-bar-animated': !progress }"
            role="progressbar"
            :style="{ width: `${progress ? progressPercent : 100}%` }"
            :aria-valuenow="progress?.done ?? 0"
            aria-valuemin="0"
            :aria-valuemax="progress?.total ?? 1"
          />
        </div>
      </div>
 
      <div v-if="rows.length === 0" class="text-muted">
        {{ t('entity.importPreviewEmpty') }}
      </div>
 
      <div v-if="rows.length > 0" class="text-muted small mb-3">
        <font-awesome-icon icon="fa-solid fa-coins" class="me-1" />
        {{ t('entity.importPreviewTotalCost').replace('{count}', String(totalEstimatedCost)) }}
        <span v-if="balance !== undefined" class="import-preview-balance">
          · {{ t('entity.importPreviewBalance').replace('{count}', String(balance)) }}
        </span>
      </div>
 
      <div v-for="row in rows" :key="row.tempId" class="import-preview-row border rounded p-3 mb-3">
        <div class="d-flex justify-content-between align-items-start gap-3 mb-2">
          <div class="flex-grow-1">
            <label class="form-label small mb-1" :for="`import-row-name-${row.tempId}`">
              {{ t('entity.importPreviewEntityName') }}
            </label>
            <input
              :id="`import-row-name-${row.tempId}`"
              v-model="row.name"
              class="form-control form-control-sm"
              type="text"
              :disabled="row.choice !== 'create' || loading"
            />
          </div>
          <div class="text-muted small text-end" style="white-space: nowrap">
            <div>
              {{ t('entity.importPreviewFieldCount').replace('{count}', String(row.fieldCount)) }}
            </div>
            <div v-if="row.itemCount > 0">
              {{ t('entity.importPreviewItemCount').replace('{count}', String(row.itemCount)) }}
            </div>
            <div v-if="row.choice !== 'skip'">
              {{ t('entity.importPreviewEstimatedCost').replace('{count}', String(rowCost(row))) }}
            </div>
          </div>
        </div>
 
        <div v-if="row.nameConflict" class="alert alert-warning py-2 px-3 small mb-2">
          <template v-if="schemaOnly">
            {{
              t('entity.importConflictRenameMessage').replace(
                '{name}',
                row.nameConflict.conflictingEntityName
              )
            }}
          </template>
          <template v-else-if="row.nameConflict.source === 'existing'">
            {{
              t('entity.importConflictCompatibleMessage').replace(
                '{name}',
                row.nameConflict.conflictingEntityName
              )
            }}
          </template>
          <template v-else>
            {{
              t('entity.importPreviewBatchConflict').replace(
                '{name}',
                row.nameConflict.conflictingEntityName
              )
            }}
          </template>
          <ul
            v-if="
              !schemaOnly &&
              !row.nameConflict.compatible &&
              row.nameConflict.missingFields.length > 0
            "
            class="mb-0 mt-1"
          >
            <li v-for="(field, index) in row.nameConflict.missingFields" :key="index">
              {{ getTranslation(field.name) }} ({{ field.type }})
            </li>
          </ul>
        </div>
        <div v-else-if="!row.valid" class="alert alert-danger py-2 px-3 small mb-2">
          {{ row.error }}
        </div>
 
        <div class="d-flex flex-wrap gap-3 align-items-center">
          <div class="btn-group btn-group-sm" role="group">
            <input
              :id="`import-row-create-${row.tempId}`"
              v-model="row.choice"
              type="radio"
              class="btn-check"
              value="create"
              :disabled="!row.valid || loading"
            />
            <label class="btn btn-outline-primary" :for="`import-row-create-${row.tempId}`">
              {{ t('entity.importPreviewChoiceCreate') }}
            </label>
 
            <input
              v-if="canMerge(row)"
              :id="`import-row-merge-${row.tempId}`"
              v-model="row.choice"
              type="radio"
              class="btn-check"
              value="merge"
              :disabled="loading"
            />
            <label
              v-if="canMerge(row)"
              class="btn btn-outline-primary"
              :for="`import-row-merge-${row.tempId}`"
            >
              {{ t('entity.importPreviewChoiceMerge') }}
            </label>
 
            <input
              :id="`import-row-skip-${row.tempId}`"
              v-model="row.choice"
              type="radio"
              class="btn-check"
              value="skip"
              :disabled="loading"
            />
            <label class="btn btn-outline-secondary" :for="`import-row-skip-${row.tempId}`">
              {{ t('entity.importPreviewChoiceSkip') }}
            </label>
          </div>
 
          <div v-if="row.itemCount > 0 && row.choice !== 'skip'" class="form-check mb-0">
            <input
              :id="`import-row-items-${row.tempId}`"
              v-model="row.includeItems"
              class="form-check-input"
              type="checkbox"
              :disabled="loading"
            />
            <label class="form-check-label small" :for="`import-row-items-${row.tempId}`">
              {{ t('entity.importPreviewIncludeItems').replace('{count}', String(row.itemCount)) }}
            </label>
          </div>
        </div>
      </div>
    </template>
 
    <!-- Post-import summary only has a single "Close" action; the editable
         preview keeps BaseFormSidebar's default Cancel/Import footer. -->
    <template v-if="results" #footer>
      <button type="button" class="btn btn-primary" @click="close">
        {{ t('common.close') }}
      </button>
    </template>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
// @implements UC-CREDITS-005.1, UC-STORE-005.1
import { reactive, computed, watch } from 'vue'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import { ITEM_ERROR_CODE_TO_I18N_KEY } from '@/utils/itemValidation'
import { renamedFieldsText } from '@/utils/renamedFields'
import type {
  ImportCheckResult,
  ImportBundleEntry,
  ImportBundleResult,
  ImportItemIssue
} from '@/stores/entities'
import type { EntityExportBundle } from '@/utils/entityExportBundle'
 
const { t } = useUILanguage()
const { getTranslation } = useLanguage()
 
// Same error-code -> i18n-key mapping used for live item create/edit errors
// (ItemFormSidebar.vue), so a rule caught at import time reads identically —
// same {field} placeholder convention, resolved via getTranslation since the
// field's own name is already stored multilingually on the schema.
function itemIssueMessage(issue: ImportItemIssue): string {
  const i18nKey = ITEM_ERROR_CODE_TO_I18N_KEY[issue.error] ?? 'item.fieldInvalidValue'
  return t(i18nKey).replace('{field}', getTranslation(issue.fieldName))
}
 
interface Props {
  isOpen: boolean
  bundle: EntityExportBundle | null
  checkResults: ImportCheckResult[]
  loading?: boolean
  error?: string
  results?: ImportBundleResult[] | null
  // Job status/progress while the import job started by `confirm` is
  // pending/processing on the server.
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: { done: number; total: number } | null
  // A bundle with no items to bring, like a Store pack: merging is not offered
  schemaOnly?: boolean
  // The caller's credits, shown next to the estimate when given
  balance?: number
  title?: string
  submitLabel?: string
}
 
const props = defineProps<Props>()
 
const isJobInProgress = computed(() => props.status === 'pending' || props.status === 'processing')
const progressPercent = computed(() => {
  Iif (!props.progress || props.progress.total <= 0) return 0
  return Math.min(100, Math.round((props.progress.done / props.progress.total) * 100))
})
const jobProgressLabel = computed(() =>
  props.progress
    ? t('entity.importProgress')
        .replace('{done}', String(props.progress.done))
        .replace('{total}', String(props.progress.total))
    : t('entity.importPreparing')
)
 
const emit = defineEmits<{
  confirm: [entries: ImportBundleEntry[]]
  cancel: []
  close: []
}>()
 
interface Row {
  tempId: string
  name: string
  fieldCount: number
  itemCount: number
  valid: boolean
  error?: string
  nameConflict: ImportCheckResult['nameConflict']
  choice: 'create' | 'merge' | 'skip'
  includeItems: boolean
}
 
const rows = reactive<Row[]>([])
 
function buildRows(): Row[] {
  Iif (!props.bundle) return []
 
  return props.bundle.entities.map((entry) => {
    const checkResult = props.checkResults.find((r) => r.tempId === entry.tempId)
    const nameConflict = checkResult?.nameConflict ?? null
    const valid = checkResult?.valid ?? true
 
    let choice: Row['choice'] = 'create'
    let name = getTranslation(entry.entity.name)
    if (!valid) {
      choice = 'skip'
    } else if (nameConflict) {
      choice =
        !props.schemaOnly && nameConflict.source === 'existing' && nameConflict.compatible
          ? 'merge'
          : 'create'
      if (choice === 'create') {
        name = `${name} (2)`
      }
    }
 
    return {
      tempId: entry.tempId,
      name,
      fieldCount: entry.entity.fields.length,
      itemCount: entry.items.length,
      valid,
      error: checkResult?.error,
      nameConflict,
      choice,
      includeItems: entry.items.length > 0
    }
  })
}
 
function canMerge(row: Row): boolean {
  return !props.schemaOnly && row.nameConflict?.source === 'existing' && row.nameConflict.compatible
}
 
// Rebuilt on opening, and when the bundle changes underneath an open panel (a
// new version of a Store pack was approved meanwhile).
watch(
  [() => props.isOpen, () => props.bundle, () => props.checkResults],
  ([open]) => {
    if (open) {
      rows.splice(0, rows.length, ...buildRows())
    }
  },
  { immediate: true }
)
 
// Client-side estimate only — mirrors the real charge computed server-side
// in entities/import-worker.js (see docs/architecture/USAGE_METERING.md
// "Gap found and closed: bulk import and entity fork bypassed credits
// entirely"), using the same rate and the same byte-counting approach
// (UTF-8 bytes of the serialized JSON, not JS string length, to match
// Node's Buffer.byteLength). The two can drift slightly: the real charge
// only counts entities/items that actually get written (a name conflict or
// per-item validation failure server-side isn't known until submit), so
// this estimate is always an upper bound, never an undercount.
const STORAGE_CREDITS_PER_KB = 2
 
function utf8ByteLength(value: unknown): number {
  return new TextEncoder().encode(JSON.stringify(value)).length
}
 
function estimateEntityCost(entity: EntityExportBundle['entities'][number]['entity']): number {
  const bytes = utf8ByteLength({ fields: entity.fields ?? [], forms: entity.forms ?? [] })
  return Math.ceil((bytes / 1024) * STORAGE_CREDITS_PER_KB)
}
 
function estimateItemsCost(items: EntityExportBundle['entities'][number]['items']): number {
  const bytes = items.reduce((sum, item) => {
    const { originalId: _originalId, ...data } = (item ?? {}) as Record<string, unknown>
    return sum + utf8ByteLength(data)
  }, 0)
  return Math.ceil((bytes / 1024) * STORAGE_CREDITS_PER_KB)
}
 
function rowCost(row: Row): number {
  const entry = props.bundle?.entities.find((e) => e.tempId === row.tempId)
  Iif (!entry) return 0
 
  let cost = 0
  if (row.choice === 'create') {
    cost += estimateEntityCost(entry.entity)
  }
  if (row.itemCount > 0 && row.includeItems) {
    cost += estimateItemsCost(entry.items)
  }
  return cost
}
 
const totalEstimatedCost = computed(() =>
  rows.filter((row) => row.choice !== 'skip').reduce((sum, row) => sum + rowCost(row), 0)
)
 
const canConfirm = computed(() => rows.some((row) => row.choice !== 'skip'))
 
function resultFor(tempId: string): ImportBundleResult | undefined {
  return props.results?.find((r) => r.tempId === tempId)
}
 
function confirm() {
  Iif (!props.bundle || props.loading || !canConfirm.value) return
 
  const entries: ImportBundleEntry[] = props.bundle.entities.map((entry) => {
    const row = rows.find((r) => r.tempId === entry.tempId)!
    return {
      tempId: entry.tempId,
      mode: row.choice,
      ...(row.choice === 'merge' && { targetEntityId: row.nameConflict?.conflictingEntityId }),
      ...(row.choice === 'create' && { name: row.name }),
      entity: entry.entity,
      items: entry.items,
      includeItems: row.itemCount > 0 && row.includeItems
    }
  })
 
  emit('confirm', entries)
}
 
// BaseFormSidebar has a single close affordance (X button,
// default-footer Cancel button) — before results exist that means "abandon
// the import" (cancel), after results exist it means "done reviewing"
// (close, which also triggers the caller's post-import refresh).
function handleClose() {
  Iif (props.loading) return
  if (props.results) {
    emit('close')
  } else {
    emit('cancel')
  }
}
 
function close() {
  emit('close')
}
</script>