All files / src/components UpgradePackSidebar.vue

98.01% Statements 148/151
92.13% Branches 164/178
97.22% Functions 70/72
98.48% Lines 130/132

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  23x                               6x                           1x                           2x                 27x                 3x   28x         3x   3x                         41x     2x               3x                   20x         3x                 20x                                 2x                     1x                         1x                       4x     1x                         2x                                     3x 3x 67x                     3x 3x     19x     1x               3x               3x   2x                       1x   3x                                               17x 17x                       17x   17x           17x 17x             17x 17x 2x               17x 17x   17x 17x     17x 21x                   17x   17x   17x 46x     6x                 13x       11x 10x       4x     17x 17x   17x 14x 18x   16x     14x 9x   17x 18x   4x     17x 18x   17x   22x 6x             17x   10x 4x           18x       22x 22x 22x 22x 34x 31x   20x 20x 20x 7x         13x             22x     23x     22x 22x 22x 22x                   17x 17x             17x 23x 44x 20x   23x 22x   16x         21x         7x 6x         26x   30x 30x 30x           4x 4x             67x 67x   22x                 2x         4x     18x       18x   7x         9x 6x       2x 2x       17x             5x 4x       3x 2x 1x      
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    storage-key="upgrade-pack-sidebar"
    :title="title"
    icon="fa-solid fa-arrows-rotate"
    panel-width="700px"
    :loading="loading"
    :submit-disabled="!canConfirm"
    :submit-label="t('store.upgradeApply')"
    submit-icon="fa-solid fa-arrows-rotate"
    submit-button-class="btn-primary"
    @close="handleClose"
    @submit="confirm"
  >
    <!-- After the upgrade: what each copy and new entity became -->
    <ul v-if="result" class="list-unstyled mb-0 upgrade-results">
      <li v-for="row in result.upgraded" :key="row.entityId" class="upgrade-result mb-2">
        <span class="badge me-2" :class="row.status === 'upgraded' ? 'bg-success' : 'bg-danger'">
          {{ t(`store.upgradeStatus.${row.status}`) }}
        </span>
        <strong>{{ copyName(row.entityId) }}</strong>
        <span v-if="row.status === 'failed'" class="text-danger small">
          — {{ failure(row.error) }}
        </span>
        <span v-else class="text-muted small">
          — {{ t('store.upgradeAddedCount').replace('{count}', String(row.addedFieldsCount)) }}
          <template v-if="(row.changedFieldsCount ?? 0) > 0">
            ·
            {{ t('store.upgradeChangedCount').replace('{count}', String(row.changedFieldsCount)) }}
          </template>
          <template v-for="section in row.changedSections ?? []" :key="section">
            · {{ t(`store.upgradeSection.${section}`) }}
          </template>
          <template v-if="row.droppedFieldsCount > 0">
            ·
            {{
              t('entity.importResultDroppedFields').replace(
                '{count}',
                String(row.droppedFieldsCount)
              )
            }}
          </template>
        </span>
      </li>
      <li v-for="row in result.results" :key="row.tempId" class="upgrade-result mb-2">
        <span class="badge me-2" :class="row.status === 'created' ? 'bg-success' : 'bg-danger'">
          {{ t(`entity.importResultStatus.${row.status}`) }}
        </span>
        <strong>{{ newEntityName(row.tempId) }}</strong>
        <span v-if="row.status === 'failed'" class="text-danger small">
          — {{ failure(row.error) }}
        </span>
      </li>
    </ul>
 
    <template v-else-if="preview">
      <div v-if="error" class="alert alert-danger" role="alert">{{ error }}</div>
      <div v-if="isJobInProgress" class="text-muted small mb-3 upgrade-progress">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ jobProgressLabel }}
      </div>
 
      <p class="text-muted small">{{ t('store.upgradeHelp') }}</p>
 
      <section
        v-for="copy in preview.copies"
        :key="copy.entityId"
        class="upgrade-copy border rounded p-3 mb-3"
      >
        <h3 class="h6 mb-2">
          {{ getTranslation(copy.name) }}
          <span class="badge bg-secondary ms-1">
            {{ t('store.versionLabel').replace('{version}', String(copy.version)) }}
          </span>
        </h3>
        <p v-if="!copy.canUpdate" class="text-muted small mb-2">
          {{ t('store.upgradeNotEditable') }}
        </p>
        <p v-if="copy.noBaseline" class="text-muted small mb-2 upgrade-no-baseline">
          {{ t('store.upgradeNoBaseline') }}
        </p>
        <p v-if="copy.canUpdate && !bringsSomething(copy)" class="text-muted small mb-2">
          {{ t('store.upgradeNothingAdded') }}
        </p>
        <div v-for="field in copy.addedFields" :key="field.fieldId" class="form-check">
          <input
            :id="`upgrade-field-${copy.entityId}-${field.fieldId}`"
            v-model="checkedFields[copy.entityId]"
            class="form-check-input upgrade-field"
            type="checkbox"
            :value="field.fieldId"
            :disabled="!copy.canUpdate || loading"
          />
          <label class="form-check-label" :for="`upgrade-field-${copy.entityId}-${field.fieldId}`">
            {{ getTranslation(field.name) }}
            <span class="text-muted small"> · {{ field.type }}</span>
            <span v-if="field.mandatory" class="badge bg-light text-dark ms-1">
              {{ t('store.mandatory') }}
            </span>
          </label>
          <!-- Field names are unique per language (UC-ENTITY-029.1) -->
          <div
            v-if="field.nameConflicts && checkedFields[copy.entityId]?.includes(field.fieldId)"
            class="upgrade-name-conflicts mt-1 mb-2"
          >
            <div
              v-for="conflict in field.nameConflicts"
              :key="conflict.language"
              class="upgrade-name-conflict small mb-2"
            >
              <p class="text-warning-emphasis mb-1">
                {{
                  t('store.upgradeNameTaken')
                    .replace('{name}', conflict.fieldName)
                    .replace('{language}', conflict.language.toUpperCase())
                }}
              </p>
              <template
                v-for="key in [conflictKey(copy.entityId, field.fieldId, conflict.language)]"
                :key="key"
              >
                <div v-if="conflict.removed" class="form-check">
                  <input
                    :id="`${key}-own`"
                    v-model="resolutions[key].mode"
                    class="form-check-input upgrade-rename-own"
                    type="radio"
                    value="renameOwn"
                    :name="key"
                    :disabled="loading"
                  />
                  <label class="form-check-label" :for="`${key}-own`">
                    {{ t('store.upgradeRenameMine').replace('{name}', conflict.fieldName) }}
                  </label>
                  <input
                    v-if="resolutions[key].mode === 'renameOwn'"
                    v-model="resolutions[key].ownName"
                    class="form-control form-control-sm mt-1 upgrade-own-name"
                    type="text"
                    :aria-label="t('store.upgradeRenameMine').replace('{name}', conflict.fieldName)"
                    :disabled="loading"
                  />
                </div>
                <div :class="{ 'form-check': conflict.removed }">
                  <input
                    v-if="conflict.removed"
                    :id="`${key}-new`"
                    v-model="resolutions[key].mode"
                    class="form-check-input upgrade-rename-new"
                    type="radio"
                    value="renameNew"
                    :name="key"
                    :disabled="loading"
                  />
                  <label :class="{ 'form-check-label': conflict.removed }" :for="`${key}-new`">
                    {{ t('store.upgradeRenameNew') }}
                  </label>
                  <input
                    v-if="resolutions[key].mode === 'renameNew'"
                    :id="conflict.removed ? undefined : `${key}-new`"
                    v-model="resolutions[key].newName"
                    class="form-control form-control-sm mt-1 upgrade-new-name"
                    type="text"
                    :aria-label="t('store.upgradeRenameNew')"
                    :disabled="loading"
                  />
                </div>
              </template>
            </div>
          </div>
        </div>
        <!-- What only the version changed since the copy took it -->
        <div v-for="change in copy.changedFields" :key="change.fieldId" class="form-check">
          <input
            :id="`upgrade-change-${copy.entityId}-${change.fieldId}`"
            v-model="checkedChanges[copy.entityId]"
            class="form-check-input upgrade-change"
            type="checkbox"
            :value="change.fieldId"
            :disabled="!copy.canUpdate || loading"
          />
          <label
            class="form-check-label"
            :for="`upgrade-change-${copy.entityId}-${change.fieldId}`"
          >
            {{ changedLabel(change) }}
          </label>
        </div>
        <div v-for="section in copy.changedSections" :key="section" class="form-check">
          <input
            :id="`upgrade-section-${copy.entityId}-${section}`"
            v-model="checkedSections[copy.entityId]"
            class="form-check-input upgrade-section"
            type="checkbox"
            :value="section"
            :disabled="!copy.canUpdate || loading"
          />
          <label class="form-check-label" :for="`upgrade-section-${copy.entityId}-${section}`">
            {{
              t('store.upgradeSectionChanged').replace(
                '{section}',
                t(`store.upgradeSection.${section}`)
              )
            }}
          </label>
        </div>
        <div v-if="copy.otherChanges.length > 0" class="small text-muted mt-2 upgrade-changes">
          <p class="mb-1">{{ t('store.upgradeNotApplied') }}</p>
          <ul class="mb-0">
            <li v-for="(change, index) in copy.otherChanges" :key="index">
              {{ changeLabel(change) }}
            </li>
          </ul>
        </div>
      </section>
 
      <section
        v-if="preview.newEntities.length > 0"
        class="upgrade-new-entities border rounded p-3"
      >
        <h3 class="h6 mb-2">{{ t('store.upgradeNewEntities') }}</h3>
        <p class="text-muted small mb-2">
          {{ preview.canCreate ? t('store.upgradeNewEntitiesHelp') : t('store.upgradeNoCreate') }}
        </p>
        <div v-for="entity in preview.newEntities" :key="entity.tempId" class="form-check">
          <input
            :id="`upgrade-entity-${entity.tempId}`"
            v-model="checkedEntities"
            class="form-check-input upgrade-entity"
            type="checkbox"
            :value="entity.tempId"
            :disabled="!preview.canCreate || loading"
          />
          <label class="form-check-label" :for="`upgrade-entity-${entity.tempId}`">
            {{ getTranslation(entity.name) }}
            <span class="text-muted small">
              · {{ t('store.fieldCount').replace('{count}', String(entity.fieldCount)) }}
            </span>
          </label>
          <div
            v-if="entity.nameTaken && checkedEntities.includes(entity.tempId)"
            class="upgrade-entity-name small mt-1 mb-2"
          >
            <p class="text-warning-emphasis mb-1">{{ t('store.errors.ENTITY_NAME_CONFLICT') }}</p>
            <input
              v-model="entityNames[entity.tempId]"
              class="form-control form-control-sm"
              type="text"
              :aria-label="t('store.upgradeEntityName')"
              :disabled="loading"
            />
          </div>
        </div>
      </section>
    </template>
 
    <template v-if="result" #footer>
      <button type="button" class="btn btn-primary" @click="emit('close')">
        {{ t('common.close') }}
      </button>
    </template>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
// @implements UC-STORE-013.1
import { computed, ref, watch } from 'vue'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import type {
  FieldNamesByLanguage,
  LocalizedText,
  PackUpgradeChange,
  PackUpgradeChangedField,
  PackUpgradeChoices,
  PackUpgradeSection,
  PackUpgradeNameConflict,
  PackUpgradePreview,
  PackUpgradeResult
} from '@/stores/packs'
import { API_ERROR_CODE_TO_I18N_KEY } from '@/utils/errors'
 
const { t } = useUILanguage()
const { getTranslation } = useLanguage()
 
interface Props {
  isOpen: boolean
  preview: PackUpgradePreview | null
  loading?: boolean
  error?: string
  result?: PackUpgradeResult | null
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: { done: number; total: number } | null
}
 
const props = defineProps<Props>()
 
const emit = defineEmits<{
  confirm: [choices: PackUpgradeChoices]
  cancel: []
  close: []
}>()
 
const title = computed(() =>
  props.preview
    ? t('store.upgradeTitle')
        .replace('{from}', String(props.preview.fromVersion))
        .replace('{to}', String(props.preview.toVersion))
    : ''
)
 
const isJobInProgress = computed(() => props.status === 'pending' || props.status === 'processing')
const jobProgressLabel = computed(() =>
  props.progress
    ? t('entity.importProgress')
        .replace('{done}', String(props.progress.done))
        .replace('{total}', String(props.progress.total))
    : t('entity.importPreparing')
)
 
// Everything the version adds starts checked: Bob unchecks what he declines
const checkedFields = ref<Record<string, string[]>>({})
const checkedEntities = ref<string[]>([])
// What only the version changed, offered the same way, checked
const checkedChanges = ref<Record<string, string[]>>({})
const checkedSections = ref<Record<string, PackUpgradeSection[]>>({})
 
type PreviewCopy = PackUpgradePreview['copies'][number]
const bringsSomething = (copy: PreviewCopy) =>
  copy.addedFields.length > 0 || copy.changedFields.length > 0 || copy.changedSections.length > 0
 
// How each name an added field shares with a field of the copy is resolved:
// renaming Bob's field, when the version removed it (the default: the new
// field keeps the name Alice gave it), or naming the new field otherwise
interface Resolution {
  mode: 'renameOwn' | 'renameNew'
  ownName: string
  newName: string
}
const resolutions = ref<Record<string, Resolution>>({})
// The name a new entity takes when the flow already has its own
const entityNames = ref<Record<string, string>>({})
 
const conflictKey = (entityId: string, fieldId: string, language: string) =>
  `upgrade-name-${entityId}-${fieldId}-${language}`
 
function initialResolution(conflict: PackUpgradeNameConflict): Resolution {
  return {
    mode: conflict.removed ? 'renameOwn' : 'renameNew',
    ownName: `${conflict.fieldName.trim()} ${t('store.upgradeOldSuffix')}`,
    newName: conflict.suggestedName
  }
}
 
// The language an entity's name is compared in (flows-api normalizeName)
function comparedLanguage(name: Record<string, string>): string {
  return name.en ? 'en' : name.fr ? 'fr' : (Object.keys(name)[0] ?? 'en')
}
 
function entityNameWith(name: LocalizedText, value: string): LocalizedText {
  if (typeof name === 'string') return value
  return { ...name, [comparedLanguage(name)]: value }
}
 
function comparedName(name: LocalizedText): string {
  return typeof name === 'string' ? name : (name[comparedLanguage(name)] ?? '')
}
 
watch(
  [() => props.isOpen, () => props.preview],
  ([open, preview]) => {
    if (!open || !preview) return
    checkedFields.value = Object.fromEntries(
      preview.copies.map((copy) => [
        copy.entityId,
        copy.canUpdate ? copy.addedFields.map((field) => field.fieldId) : []
      ])
    )
    checkedEntities.value = preview.canCreate
      ? preview.newEntities.map((entity) => entity.tempId)
      : []
    checkedChanges.value = Object.fromEntries(
      preview.copies.map((copy) => [
        copy.entityId,
        copy.canUpdate ? copy.changedFields.map((change) => change.fieldId) : []
      ])
    )
    checkedSections.value = Object.fromEntries(
      preview.copies.map((copy) => [copy.entityId, copy.canUpdate ? [...copy.changedSections] : []])
    )
    resolutions.value = Object.fromEntries(
      preview.copies.flatMap((copy) =>
        copy.addedFields.flatMap((field) =>
          (field.nameConflicts ?? []).map((conflict) => [
            conflictKey(copy.entityId, field.fieldId, conflict.language),
            initialResolution(conflict)
          ])
        )
      )
    )
    entityNames.value = Object.fromEntries(
      preview.newEntities
        .filter((entity) => entity.nameTaken)
        .map((entity) => [entity.tempId, `${comparedName(entity.name).trim()} (2)`])
    )
  },
  { immediate: true }
)
 
const updatableCopies = computed(() => props.preview?.copies.filter((copy) => copy.canUpdate) ?? [])
 
// The names each copy's checked fields take, and the renames of its fields
function namesFor(copy: PackUpgradePreview['copies'][number]) {
  const fieldNames: FieldNamesByLanguage = {}
  const renames: FieldNamesByLanguage = {}
  const checked = checkedFields.value[copy.entityId] ?? []
  for (const field of copy.addedFields) {
    if (!checked.includes(field.fieldId)) continue
    for (const conflict of field.nameConflicts ?? []) {
      const resolution =
        resolutions.value[conflictKey(copy.entityId, field.fieldId, conflict.language)]
      Iif (!resolution) continue
      if (resolution.mode === 'renameOwn') {
        renames[conflict.fieldId] = {
          ...renames[conflict.fieldId],
          [conflict.language]: resolution.ownName.trim()
        }
      } else {
        fieldNames[field.fieldId] = {
          ...fieldNames[field.fieldId],
          [conflict.language]: resolution.newName.trim()
        }
      }
    }
  }
  return { fieldNames, renames }
}
 
const choices = computed<PackUpgradeChoices>(() => ({
  // Every copy that may be updated moves to the version, with the fields checked
  copies: updatableCopies.value.map((copy) => {
    const { fieldNames, renames } = namesFor(copy)
    const changedFieldIds = checkedChanges.value[copy.entityId] ?? []
    const sections = checkedSections.value[copy.entityId] ?? []
    return {
      entityId: copy.entityId,
      fieldIds: checkedFields.value[copy.entityId] ?? [],
      ...(Object.keys(fieldNames).length > 0 && { fieldNames }),
      ...(Object.keys(renames).length > 0 && { renames }),
      ...(changedFieldIds.length > 0 && { changedFieldIds }),
      ...(sections.length > 0 && { sections })
    }
  }),
  entities: checkedEntities.value.map((tempId) => {
    const entity = props.preview?.newEntities.find((e) => e.tempId === tempId)
    return entity?.nameTaken
      ? { tempId, name: entityNameWith(entity.name, (entityNames.value[tempId] ?? '').trim()) }
      : { tempId }
  })
}))
 
// Every name asked for is given
const namesGiven = computed(() => {
  const given = (names?: FieldNamesByLanguage) =>
    Object.values(names ?? {}).every((byLanguage) =>
      Object.values(byLanguage).every((name) => name.length > 0)
    )
  return (
    choices.value.copies.every((copy) => given(copy.fieldNames) && given(copy.renames)) &&
    checkedEntities.value.every(
      (tempId) => !(tempId in entityNames.value) || entityNames.value[tempId].trim().length > 0
    )
  )
})
 
const canConfirm = computed(
  () => (updatableCopies.value.length > 0 || checkedEntities.value.length > 0) && namesGiven.value
)
 
function confirm() {
  if (!props.preview || props.loading || !canConfirm.value) return
  emit('confirm', choices.value)
}
 
// "options, mandatory": the properties of a definition, by their UI names
function propertiesText(properties: string[] = []): string {
  return properties
    .map((property) => {
      const key = `store.fieldProperty.${property}`
      const label = t(key)
      return label === key ? property : label
    })
    .join(', ')
}
 
function changedLabel(change: PackUpgradeChangedField): string {
  const renamed = change.properties.includes('name')
  return t(renamed ? 'store.upgradeChangedRenamed' : 'store.upgradeChanged')
    .replace('{name}', getTranslation(change.name))
    .replace('{packName}', getTranslation(change.packName))
    .replace('{properties}', propertiesText(change.properties))
}
 
function changeLabel(change: PackUpgradeChange): string {
  const name = getTranslation(change.name ?? '')
  switch (change.change) {
    case 'conflict':
      return change.section
        ? t('store.upgradeSectionConflict').replace(
            '{section}',
            t(`store.upgradeSection.${change.section}`)
          )
        : t('store.upgradeChangeConflict')
            .replace('{name}', name)
            .replace('{properties}', propertiesText(change.properties))
    case 'manual':
      return t('store.upgradeChangeManual')
        .replace('{name}', name)
        .replace('{properties}', propertiesText(change.properties))
        .replace(
          '{reasons}',
          (change.reasons ?? []).map((reason) => t(`store.manualReason.${reason}`)).join(', ')
        )
    case 'retyped':
      return t('store.upgradeChangeRetyped')
        .replace('{name}', name)
        .replace('{type}', change.packType ?? '')
    case 'removed':
      return t('store.upgradeChangeRemoved').replace('{name}', name)
    default:
      return t('store.upgradeChangeEntityRemoved')
  }
}
 
function copyName(entityId: string): string {
  const copy = props.preview?.copies.find((c) => c.entityId === entityId)
  return copy ? getTranslation(copy.name) : entityId
}
 
function newEntityName(tempId: string): string {
  const entity = props.preview?.newEntities.find((e) => e.tempId === tempId)
  return entity ? getTranslation(entity.name) : tempId
}
 
// The worker's codes, never shown as they are
const FAILURE_KEYS: Record<string, string> = {
  ENTITY_CHANGED: 'store.errors.ENTITY_CHANGED',
  ENTITY_NAME_CONFLICT: 'store.errors.ENTITY_NAME_CONFLICT',
  ...API_ERROR_CODE_TO_I18N_KEY
}
 
function failure(error?: string): string {
  if (!error) return t('store.upgradeError')
  return FAILURE_KEYS[error] ? t(FAILURE_KEYS[error]) : error
}
 
function handleClose() {
  if (props.loading) return
  if (props.result) emit('close')
  else emit('cancel')
}
</script>