All files / src/components PublishPackSidebar.vue

98.18% Statements 216/220
91.71% Branches 144/157
100% Functions 55/55
100% Lines 190/190

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  108x                     1x     208x         1x         3x   54x                                                 3x   2x                       3x 3x 324x     23x                                         1x                     3x 3x 138x             4x                   3x 3x     81x     2x                                             2x                         3x   1x                 3x     1x                 3x     3x                                         3x   3x           84x 84x   40x 40x       34x                 34x         34x 34x 34x 34x 34x       34x 34x 34x   34x 73x     69x     34x 34x         34x 34x 34x 34x 34x 34x   34x   34x 34x 34x 95x 66x       34x 61x 4x     34x 34x 34x   34x 34x 34x 34x 66x 34x   66x 34x   120x                 72x 8x         36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x     34x   37x 37x 37x 37x     36x 36x 102x   36x 37x   1x   37x             4x 4x 3x 3x 6x 2x 4x 2x 2x 2x   2x   1x       34x   34x 43x   43x 36x 36x 36x 36x         34x 34x     30x 30x 6x 6x 6x 6x   24x 24x 24x 23x 23x 62x 23x 2x 2x 2x 2x   4x           23x 4x     1x 1x   24x             4x 1x             34x     7x 7x 7x 6x     1x       34x     62x 62x 62x 62x 62x 62x 30x           10x 10x 10x 1x       9x 1x         8x 2x   6x 1x       5x 2x       3x 1x       18x 18x 18x 18x 18x                                 8x   10x   18x        
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    storage-key="publish-pack-sidebar"
    :title="title"
    icon="fa-solid fa-store"
    panel-width="700px"
    :loading="loading"
    :submit-disabled="!canSubmit"
    :submit-label="t('store.publishSubmit')"
    submit-icon="fa-solid fa-store"
    submit-button-class="btn-primary"
    @close="$emit('cancel')"
    @submit="submit"
  >
    <p class="text-muted small">{{ t('store.publishHelp') }}</p>
    <div v-if="error" class="alert alert-danger publish-error" role="alert">{{ error }}</div>
 
    <EditingLanguageSelector
      v-if="enabledLanguages.length > 1"
      v-model="editingLanguage"
      :languages="enabledLanguages"
      class="mb-3 pack-languages"
    />
 
    <div class="mb-3">
      <MultilingualInput
        v-model="name"
        input-id="pack-name"
        :label="t('store.nameLabel')"
        :default-language="defaultLanguage"
        :enabled-languages="enabledLanguages"
        :current-language="editingLanguage"
        :show-language-selector="false"
        :maxlength="100"
        required
      />
      <div v-if="publication?.refusal" class="text-danger small mt-1 pack-name-refusal">
        {{ t(`store.errors.${publication.refusal}`) }}
      </div>
      <div
        v-else-if="publication && publication.isNewPack === false"
        class="text-primary small mt-1 pack-next-version"
      >
        {{
          t('store.nextVersion')
            .replace('{version}', String(publication.version))
            .replace('{name}', getTranslation(cleanName))
        }}
      </div>
    </div>
 
    <div class="mb-3">
      <MultilingualTextarea
        v-model="description"
        input-id="pack-description"
        :label="t('store.descriptionLabel')"
        :default-language="defaultLanguage"
        :enabled-languages="enabledLanguages"
        :current-language="editingLanguage"
        :show-language-selector="false"
        :rows="3"
        :maxlength="1000"
      />
    </div>
 
    <fieldset class="mb-3">
      <legend class="form-label fs-6">{{ t('store.entitiesLabel') }}</legend>
      <div v-for="entity in listedEntities" :key="entity.id" class="form-check">
        <input
          :id="`pack-entity-${entity.id}`"
          v-model="selectedIds"
          class="form-check-input pack-entity-choice"
          type="checkbox"
          :value="entity.id"
          :disabled="loading"
        />
        <label class="form-check-label" :for="`pack-entity-${entity.id}`">
          {{ getTranslation(entity.name) }}
        </label>
      </div>
      <div v-if="loadingEntities" class="small text-muted pack-entities-loading">
        <span class="spinner-border spinner-border-sm me-2" aria-hidden="true" />
        {{ t('common.loading') }}
      </div>
      <p v-else-if="listedEntities.length === 0" class="small text-muted mb-0 pack-entities-empty">
        {{ t('store.noEntities') }}
      </p>
      <button
        v-if="entitiesNextToken && !loadingEntities"
        type="button"
        class="btn btn-link btn-sm px-0 pack-entities-more"
        @click="loadEntities(true)"
      >
        {{ t('common.loadMore') }}
      </button>
    </fieldset>
 
    <div v-if="discovering" class="small text-muted mb-3">
      <span class="spinner-border spinner-border-sm me-2" aria-hidden="true" />
      {{ t('common.loading') }}
    </div>
    <div v-else-if="dependencies.length > 0" class="mb-3 pack-dependencies">
      <p class="form-label mb-1">{{ t('store.dependenciesLabel') }}</p>
      <p class="small text-muted mb-2">{{ t('store.dependenciesHelp') }}</p>
      <div v-for="dependency in dependencies" :key="dependency.id" class="form-check">
        <input
          :id="`pack-dependency-${dependency.id}`"
          class="form-check-input pack-dependency-choice"
          type="checkbox"
          :checked="!excludedIds.includes(dependency.id)"
          :disabled="loading"
          @change="toggleDependency(dependency.id)"
        />
        <label class="form-check-label" :for="`pack-dependency-${dependency.id}`">
          {{ dependency.name }}
        </label>
      </div>
    </div>
 
    <!-- Items for linked entities (reference lists), never to replicate content -->
    <div v-if="itemsCandidates.length > 0" class="mb-3 pack-items">
      <p class="form-label mb-1">{{ t('store.itemsLabel') }}</p>
      <p class="small text-muted mb-2">
        {{ t('store.itemsHelp').replace('{max}', String(MAX_PACK_ITEMS_PER_ENTITY)) }}
      </p>
      <div v-for="entity in itemsCandidates" :key="entity.id" class="form-check">
        <input
          :id="`pack-items-${entity.id}`"
          v-model="itemsIds"
          class="form-check-input pack-items-choice"
          type="checkbox"
          :value="entity.id"
          :disabled="loading || entity.itemCount > MAX_PACK_ITEMS_PER_ENTITY"
        />
        <label class="form-check-label" :for="`pack-items-${entity.id}`">
          {{
            t('store.itemsChoice')
              .replace('{name}', entity.name)
              .replace('{count}', String(entity.itemCount))
          }}
          <span
            v-if="entity.itemCount > MAX_PACK_ITEMS_PER_ENTITY"
            class="d-block small text-danger pack-items-too-many"
          >
            {{ t('store.itemsTooMany').replace('{max}', String(MAX_PACK_ITEMS_PER_ENTITY)) }}
          </span>
        </label>
      </div>
      <div v-if="itemsIds.length > 0" class="form-check mt-2">
        <input
          id="pack-items-confirmed"
          v-model="itemsConfirmed"
          class="form-check-input pack-items-confirmed"
          type="checkbox"
          :disabled="loading"
        />
        <label class="form-check-label" for="pack-items-confirmed">
          {{ t('store.itemsConfirm') }}
        </label>
      </div>
    </div>
 
    <!-- A new pack's picture, on its card; a new version keeps the pack's, changed from its page -->
    <div v-if="!props.pack" class="mb-3 pack-picture-choice">
      <label class="form-label">{{ t('store.pictureLabel') }}</label>
      <ImageField
        v-model="picture"
        :field="{ name: 'picture', type: 'image', fieldId: 'pack-picture' }"
        :is-editing="!loading"
        :pack-id="draftPackId"
      />
    </div>
 
    <!-- A new version keeps the pack's setting, changed from the pack's page -->
    <div v-if="!props.pack" class="mb-3">
      <div class="form-check">
        <input
          id="pack-comments-enabled"
          v-model="commentsEnabled"
          class="form-check-input pack-comments-choice"
          type="checkbox"
          :disabled="loading"
        />
        <label class="form-check-label" for="pack-comments-enabled">
          {{ t('store.commentsEnabledLabel') }}
        </label>
      </div>
      <div class="form-text">{{ t('store.commentsEnabledHelp') }}</div>
    </div>
 
    <p class="small text-muted mb-0">{{ t('store.schemaOnlyNotice') }}</p>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
// @implements UC-STORE-003.1, UC-STORE-008.2, UC-STORE-009.1
// Opened from the Store for a new pack, or from a pack for its next version,
// which starts from what the current one was published from
import { computed, ref, watch } from 'vue'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import MultilingualInput from '@/components/MultilingualInput.vue'
import MultilingualTextarea from '@/components/MultilingualTextarea.vue'
import ImageField from '@/components/ImageField.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import { useAuthStore } from '@/stores/auth'
import { useEntitiesStore, type Entity, type ExportDiscoveredEntity } from '@/stores/entities'
import { usePacksStore, type PackDetail, type PackPublication } from '@/stores/packs'
import { getErrorMessage } from '@/utils/errors'
import EditingLanguageSelector from './EditingLanguageSelector.vue'
 
const CHECK_DELAY_MS = 400
// A pack carries items for linked entities only (flows-api utils/packs.js)
const MAX_PACK_ITEMS_PER_ENTITY = 20
 
type LocalizedText = string | Record<string, string>
 
/** Trimmed translations, empty ones dropped: what the API stores. */
function cleanText(value: LocalizedText): Record<string, string> {
  const source = typeof value === 'string' ? { [defaultLanguage.value]: value } : value
  return Object.fromEntries(
    Object.entries(source)
      .map(([lang, text]) => [lang, text.trim()] as const)
      .filter(([, text]) => text.length > 0)
  )
}
 
const props = withDefaults(
  defineProps<{
    isOpen: boolean
    // The pack whose next version this publishes; none publishes a new pack
    pack?: PackDetail | null
  }>(),
  { pack: null }
)
 
const emit = defineEmits<{
  cancel: []
  published: [result: { id: string; version: number }]
}>()
 
const { t } = useUILanguage()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const authStore = useAuthStore()
const entitiesStore = useEntitiesStore()
const packsStore = usePacksStore()
 
type ListedEntity = Pick<Entity, 'id' | 'name'>
// The flow's own entities, a page at a time: a pack never publishes a linked one
const flowEntities = ref<ListedEntity[]>([])
const entitiesNextToken = ref<string | null>(null)
const loadingEntities = ref(false)
// The previous version's entities still in the flow, chosen before their page is listed
const sourceEntities = ref<ListedEntity[]>([])
const listedEntities = computed(() => [
  ...sourceEntities.value,
  ...flowEntities.value.filter(
    (entity) => !sourceEntities.value.some((source) => source.id === entity.id)
  )
])
const title = computed(() =>
  props.pack
    ? t('store.publishVersionTitle').replace('{name}', getTranslation(props.pack.name))
    : t('store.publishTitle')
)
 
const name = ref<LocalizedText>({})
const description = ref<LocalizedText>({})
const editingLanguage = ref(defaultLanguage.value)
const selectedIds = ref<string[]>([])
const excludedIds = ref<string[]>([])
const dependencies = ref<ExportDiscoveredEntity[]>([])
// Every entity of the pack, chosen or linked, with its item count
const discovered = ref<ExportDiscoveredEntity[]>([])
// The entities whose items the pack carries, which the publisher picks
const itemsIds = ref<string[]>([])
const itemsConfirmed = ref(false)
const itemsCandidates = computed(() =>
  discovered.value.filter(
    (entity) => entity.itemCount > 0 && !excludedIds.value.includes(entity.id)
  )
)
// Items left out of the pack are no longer chosen
watch(itemsCandidates, (candidates) => {
  itemsIds.value = itemsIds.value.filter((id) =>
    candidates.some((entity) => entity.id === id && entity.itemCount <= MAX_PACK_ITEMS_PER_ENTITY)
  )
})
const discovering = ref(false)
const publication = ref<PackPublication | null>(null)
const commentsEnabled = ref(true)
// A new pack's id, chosen here so that its picture is uploaded under it first
const draftPackId = ref(crypto.randomUUID())
const picture = ref<string | null>(null)
const loading = ref(false)
const error = ref('')
const cleanName = computed(() => cleanText(name.value))
const chosenPackId = computed(() => props.pack?.id ?? '')
// What the check depends on, so that it is not sent for nothing
const checkKey = computed(() => JSON.stringify([cleanName.value, chosenPackId.value]))
const canSubmit = computed(
  () =>
    Object.keys(cleanName.value).length > 0 &&
    selectedIds.value.length > 0 &&
    (itemsIds.value.length === 0 || itemsConfirmed.value) &&
    !publication.value?.refusal &&
    !discovering.value
)
 
/** A pack's text as the inputs edit it: by language. */
function editableText(value: LocalizedText | undefined): Record<string, string> {
  if (!value) return {}
  return typeof value === 'string' ? { [defaultLanguage.value]: value } : { ...value }
}
 
function reset() {
  // A new version starts from the pack's current name and description, to change at will
  name.value = editableText(props.pack?.name)
  description.value = editableText(props.pack?.description)
  editingLanguage.value = defaultLanguage.value
  selectedIds.value = []
  sourceEntities.value = []
  flowEntities.value = []
  entitiesNextToken.value = null
  excludedIds.value = []
  dependencies.value = []
  discovered.value = []
  itemsIds.value = []
  itemsConfirmed.value = false
  publication.value = null
  commentsEnabled.value = true
  draftPackId.value = crypto.randomUUID()
  picture.value = null
  error.value = ''
}
 
let entitiesRequest = 0
async function loadEntities(more = false) {
  const request = more ? entitiesRequest : ++entitiesRequest
  loadingEntities.value = true
  try {
    const page = await entitiesStore.fetchEntitiesPage(
      more ? (entitiesNextToken.value ?? undefined) : undefined
    )
    Iif (request !== entitiesRequest) return
    const own = page.items.filter(
      (entity) => entity.flowId === authStore.currentFlow && !entity.linked
    )
    flowEntities.value = more ? [...flowEntities.value, ...own] : own
    entitiesNextToken.value = page.nextToken
  } catch (err) {
    Eif (request === entitiesRequest) error.value = getErrorMessage(err, t('store.publishError'), t)
  } finally {
    Eif (request === entitiesRequest) loadingEntities.value = false
  }
}
 
// What the current version was published from, checked again: an entity
// deleted since is left out (at most a pack's 20 entities are read)
async function startFromSource(pack: PackDetail) {
  const source = pack.source
  if (!source || source.entityIds.length === 0) return
  const request = entitiesRequest
  try {
    const found = await Promise.all(source.entityIds.map((id) => entitiesStore.findEntity(id)))
    Iif (request !== entitiesRequest || !props.isOpen) return
    const still = found.filter((entity): entity is Entity => entity !== null)
    sourceEntities.value = still.map((entity) => ({ id: entity.id, name: entity.name }))
    excludedIds.value = [...source.excludeEntityIds]
    selectedIds.value = still.map((entity) => entity.id)
    // Kept once the dependencies are known; confirming again that they may be shared
    pendingItemsIds = [...source.itemsEntityIds]
  } catch (err) {
    Eif (request === entitiesRequest) error.value = getErrorMessage(err, t('store.publishError'), t)
  }
}
// The items to carry again, chosen once the discovery lists their entities
let pendingItemsIds: string[] = []
 
watch(
  () => props.isOpen,
  (open) => {
    if (!open) return
    pendingItemsIds = []
    reset()
    loadEntities()
    if (props.pack) startFromSource(props.pack)
  },
  { immediate: true }
)
 
let discoverRequest = 0
watch(
  selectedIds,
  async (ids) => {
    const request = ++discoverRequest
    if (ids.length === 0) {
      dependencies.value = []
      discovered.value = []
      excludedIds.value = []
      return
    }
    discovering.value = true
    try {
      const { entities } = await entitiesStore.discoverExportBundle(ids)
      Iif (request !== discoverRequest) return
      discovered.value = entities
      dependencies.value = entities.filter((entity) => !entity.isRoot)
      if (pendingItemsIds.length > 0) {
        const carried = pendingItemsIds
        pendingItemsIds = []
        itemsIds.value = carried.filter((id) =>
          entities.some(
            (entity) =>
              entity.id === id &&
              entity.itemCount > 0 &&
              entity.itemCount <= MAX_PACK_ITEMS_PER_ENTITY
          )
        )
      }
      excludedIds.value = excludedIds.value.filter((id) =>
        dependencies.value.some((dependency) => dependency.id === id)
      )
    } catch (err) {
      Eif (request === discoverRequest)
        error.value = getErrorMessage(err, t('store.publishError'), t)
    } finally {
      Eif (request === discoverRequest) discovering.value = false
    }
  },
  { deep: true }
)
 
function toggleDependency(id: string) {
  excludedIds.value = excludedIds.value.includes(id)
    ? excludedIds.value.filter((excluded) => excluded !== id)
    : [...excludedIds.value, id]
}
 
// Says what publishing would do before anything is confirmed: the version it
// creates, or that another pack of the flow holds the name.
let checkTimer: ReturnType<typeof setTimeout> | undefined
let checkRequest = 0
 
async function checkName(value: Record<string, string>, forPack: string) {
  const request = ++checkRequest
  try {
    const result = await packsStore.checkName(value, forPack || undefined)
    Eif (request === checkRequest) publication.value = result
  } catch {
    // The check only informs: publishing still gets the real answer.
    Eif (request === checkRequest) publication.value = null
  }
}
 
watch(
  checkKey,
  () => {
    clearTimeout(checkTimer)
    checkRequest++
    publication.value = null
    const value = cleanName.value
    const forPack = chosenPackId.value
    if (Object.keys(value).length === 0) return
    checkTimer = setTimeout(() => checkName(value, forPack), CHECK_DELAY_MS)
  },
  { immediate: true }
)
 
function publishError(err: any): string {
  const data = err?.response?.data
  const code = data?.error
  if (code === 'PACK_MANDATORY_REFERENCE') {
    return t('store.errors.PACK_MANDATORY_REFERENCE')
      .replace('{field}', getTranslation(data.fieldName))
      .replace('{entity}', getTranslation(data.entityName))
  }
  if (code === 'PACK_ENTITY_NOT_EDITABLE') {
    return t('store.errors.PACK_ENTITY_NOT_EDITABLE').replace(
      '{entity}',
      getTranslation(data.entityName)
    )
  }
  if (code === 'PACK_TOO_MANY_ENTITIES' || code === 'PACK_TOO_MANY_FILES') {
    return t(`store.errors.${code}`).replace('{max}', String(data.max))
  }
  if (code === 'PACK_TOO_MANY_ITEMS') {
    return t('store.errors.PACK_TOO_MANY_ITEMS')
      .replace('{entity}', getTranslation(data.entityName))
      .replace('{max}', String(data.max))
  }
  if (code === 'PACK_ITEMS_MEMBER_FIELD' || code === 'PACK_ITEMS_REFERENCE') {
    return t(`store.errors.${code}`)
      .replace('{field}', getTranslation(data.fieldName))
      .replace('{entity}', getTranslation(data.entityName))
  }
  if (typeof code === 'string' && code.startsWith('PACK_')) return t(`store.errors.${code}`)
  return getErrorMessage(err, t('store.publishError'), t)
}
 
async function submit() {
  Iif (!canSubmit.value || loading.value) return
  loading.value = true
  error.value = ''
  try {
    const result = await packsStore.publish({
      name: cleanName.value,
      description: cleanText(description.value),
      entityIds: selectedIds.value,
      excludeEntityIds: excludedIds.value,
      ...(itemsIds.value.length > 0 && {
        itemsEntityIds: itemsIds.value,
        itemsConfirmed: itemsConfirmed.value
      }),
      ...(props.pack
        ? { packId: props.pack.id }
        : {
            id: draftPackId.value,
            commentsEnabled: commentsEnabled.value,
            ...(typeof picture.value === 'string' && picture.value && { picture: picture.value })
          })
    })
    emit('published', result)
  } catch (err: any) {
    error.value = publishError(err)
  } finally {
    loading.value = false
  }
}
</script>