All files / src/components MembershipRequestsPanel.vue

98.62% Statements 143/145
91.85% Branches 124/135
97.29% Functions 36/37
100% Lines 123/123

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  129x   258x             1x                         29x     75x           1x   1x 1x           1x                                                                                     1x             9x                   3x                 2x                       1x                           1x                             1x 1x                               1x                                                         23x             23x   23x   23x 23x 23x 23x   23x 23x 23x 23x 23x 23x 23x   23x 23x 23x 23x 23x     25x 25x 25x 25x         24x 25x   1x 1x   25x           23x 20x 20x     23x 23x 23x   23x           23x 23x 2x 23x     63x     463x 397x 331x 265x           1x 23x 181x 23x 153x             340x 340x 339x 338x 157x 340x 153x 150x       72x 340x 340x 340x 340x                                 75x       5x       9x 9x 9x 15x 9x       6x 6x 2x 2x         4x 3x 2x 1x       8x 8x 8x 1x 1x   7x 7x 7x 7x 1x 1x 1x 8x   6x   7x               5x 5x 5x 3x 3x     3x     2x 2x   5x         1x 1x 1x     23x                                                          
<template>
  <div class="membership-requests" data-testid="membership-requests">
    <div class="btn-group mb-3" role="group" :aria-label="t('member.requestsFilter')">
      <button
        v-for="option in STATUSES"
        :key="option"
        type="button"
        class="btn btn-outline-secondary"
        :class="{ active: status === option }"
        :data-testid="`requests-filter-${option}`"
        @click="status = option"
      >
        {{ t(option === 'pending' ? 'member.requestsPending' : 'member.requestsBanned') }}
      </button>
    </div>
 
    <LoadingSpinner v-if="loading && requests.length === 0" />
 
    <div v-else-if="loadError" class="alert alert-danger" role="alert">
      {{ t('member.requestsLoadError') }}
    </div>
 
    <EmptyState v-else-if="requests.length === 0" variant="info" data-testid="requests-empty">
      {{ t(status === 'pending' ? 'member.requestsEmpty' : 'member.requestsBannedEmpty') }}
    </EmptyState>
 
    <div
      v-for="request in requests"
      :key="request.userId"
      class="card mb-2"
      data-testid="membership-request"
    >
      <div class="card-body d-flex flex-wrap gap-3 align-items-start">
        <UserAvatar :picture-key="request.profilePicture" :size="40" />
        <div class="flex-grow-1 min-w-0">
          <div class="fw-semibold">
            {{ request.name || request.userId }}
            <span v-if="request.nickname" class="text-muted fw-normal"
              >@{{ request.nickname }}</span
            >
          </div>
          <div class="small text-muted">
            {{
              t(status === 'pending' ? 'member.requestedOn' : 'member.bannedOn').replace(
                '{date}',
                formatDate(status === 'pending' ? request.createdAt : request.decidedAt)
              )
            }}
          </div>
          <dl
            v-if="request.answers && Object.keys(request.answers).length > 0"
            class="request-answers small mb-0 mt-2"
          >
            <template v-for="answer in answerRows(request.answers)" :key="answer.fieldId">
              <dt>{{ answer.label }}</dt>
              <!-- A request's images and files (UC-SPACE-020.1) -->
              <dd
                v-if="answer.upload === 'image'"
                class="request-images"
                :data-testid="`request-image-${answer.fieldId}`"
              >
                <ImageField
                  :model-value="answer.raw as ImageAnswer"
                  :field="answer.field"
                  :is-editing="false"
                  no-wrapper
                />
              </dd>
              <dd
                v-else-if="answer.upload === 'file'"
                :data-testid="`request-file-${answer.fieldId}`"
              >
                <FileField
                  :model-value="answer.raw as FileAnswer"
                  :field="answer.field"
                  :is-editing="false"
                  no-wrapper
                />
              </dd>
              <dd v-else>{{ answer.value }}</dd>
            </template>
          </dl>
        </div>
 
        <div class="d-flex flex-wrap gap-2">
          <template v-if="status === 'pending'">
            <button
              type="button"
              class="btn btn-sm btn-success"
              :disabled="busyUserId === request.userId"
              data-testid="request-approve"
              @click="openApprove(request)"
            >
              <font-awesome-icon icon="fa-solid fa-user-check" class="me-1" />
              {{ t('member.approve') }}
            </button>
            <button
              type="button"
              class="btn btn-sm btn-outline-secondary"
              :disabled="busyUserId === request.userId"
              data-testid="request-refuse"
              @click="decide(request, 'refuse')"
            >
              {{ t('member.refuse') }}
            </button>
            <button
              type="button"
              class="btn btn-sm btn-outline-danger"
              :disabled="busyUserId === request.userId"
              data-testid="request-ban"
              @click="confirmBan.request = request"
            >
              <font-awesome-icon icon="fa-solid fa-ban" class="me-1" />
              {{ t('member.ban') }}
            </button>
          </template>
          <button
            v-else
            type="button"
            class="btn btn-sm btn-outline-secondary"
            :disabled="busyUserId === request.userId"
            data-testid="request-unban"
            @click="decide(request, 'unban')"
          >
            {{ t('member.unban') }}
          </button>
        </div>
      </div>
    </div>
 
    <button
      v-if="nextToken"
      type="button"
      class="btn btn-outline-secondary w-100"
      :disabled="loading"
      data-testid="requests-load-more"
      @click="load(false)"
    >
      {{ t('common.loadMore') }}
    </button>
 
    <MemberFormSidebar
      :is-open="!!approving"
      :member="approving"
      :available-roles="approvalRoles"
      :selected-roles="approveRoles"
      :loading="approveLoading"
      :error="approveError"
      :title="t('member.approveTitle')"
      :submit-label="t('member.approve')"
      submit-icon="fa-solid fa-user-check"
      @update:selected-roles="approveRoles = $event"
      @close="approving = null"
      @submit="approve"
    />
 
    <ConfirmModal
      :is-open="!!confirmBan.request"
      :title="t('member.banTitle')"
      :message="
        t('member.banMessage').replace(
          '{name}',
          confirmBan.request?.name || confirmBan.request?.userId || ''
        )
      "
      :confirm-label="t('member.ban')"
      variant="danger"
      @confirm="banConfirmed"
      @cancel="confirmBan.request = null"
    />
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-SPACE-005.1, UC-SPACE-006.1, UC-SPACE-020.1
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import ConfirmModal from '@/components/ConfirmModal.vue'
import EmptyState from '@/components/EmptyState.vue'
import FileField from '@/components/FileField.vue'
import ImageField from '@/components/ImageField.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import MemberFormSidebar from '@/components/MemberFormSidebar.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import { useToastStore } from '@/stores/toast'
import { useEntitiesStore, type EntityField, type FileValue } from '@/stores/entities'
import type { Role } from '@/stores/roles'
import {
  decideMembershipRequest,
  listMembershipRequests,
  type MembershipDecision,
  type MembershipRequest
} from '@/services/membershipRequests'
import type { FlowSpaceJoin } from '@/utils/spaceTheme'
 
const props = defineProps<{
  flowId: string
  /** The flow's join settings: the membership entity labels the answers, the default role is pre-selected */
  join?: FlowSpaceJoin
  roles: Role[]
}>()
 
const emit = defineEmits<{ approved: [] }>()
 
const STATUSES = ['pending', 'banned'] as const
 
const { t } = useUILanguage()
const { getTranslation } = useLanguage()
const toastStore = useToastStore()
const entitiesStore = useEntitiesStore()
 
const status = ref<(typeof STATUSES)[number]>('pending')
const requests = ref<MembershipRequest[]>([])
const nextToken = ref<string | null>(null)
const loading = ref(false)
const loadError = ref(false)
const busyUserId = ref<string | null>(null)
const fields = ref<EntityField[]>([])
 
const approving = ref<MembershipRequest | null>(null)
const approveRoles = ref<string[]>([])
const approveLoading = ref(false)
const approveError = ref('')
const confirmBan = reactive<{ request: MembershipRequest | null }>({ request: null })
 
async function load(reset = true) {
  loading.value = true
  loadError.value = false
  try {
    const page = await listMembershipRequests(
      props.flowId,
      status.value,
      reset ? null : nextToken.value
    )
    requests.value = reset ? page.requests : [...requests.value, ...page.requests]
    nextToken.value = page.nextToken
  } catch (err) {
    console.error('[MembershipRequestsPanel] failed to load requests:', err)
    loadError.value = true
  } finally {
    loading.value = false
  }
}
 
/** The membership entity's field names; without read access, the answers keep their ids */
async function loadFields() {
  if (!props.join?.entityId) return
  const entity = await entitiesStore.findEntity(props.join.entityId).catch(() => null)
  fields.value = entity?.fields ?? []
}
 
onMounted(() => {
  void load()
  void loadFields()
})
watch(status, () => load())
 
/**
 * The roles offered on approval. An approver without `roles:list` sees no roles:
 * the default role is still offered, so the request can be approved.
 */
const approvalRoles = computed<Array<Pick<Role, 'roleId' | 'name'>>>(() => {
  if (props.roles.length > 0) return props.roles
  const defaultRole = props.join?.defaultRoleId
  return defaultRole ? [{ roleId: defaultRole, name: t('space.joinDefaultRole') }] : []
})
 
const fieldsById = computed(() => new Map(fields.value.map((field) => [field.fieldId, field])))
 
function formatValue(value: unknown): string {
  if (typeof value === 'boolean') return value ? t('common.yes') : t('common.no')
  if (Array.isArray(value)) return value.map(formatValue).join(', ')
  if (value && typeof value === 'object') return getTranslation(value as Record<string, string>)
  return String(value ?? '')
}
 
type ImageAnswer = string | string[]
type FileAnswer = FileValue | FileValue[]
 
const REQUEST_FILE_PREFIX = 'membership-requests/'
const isRequestKey = (value: unknown) =>
  typeof value === 'string' && value.startsWith(REQUEST_FILE_PREFIX)
const isRequestFile = (value: unknown) =>
  !!value && typeof value === 'object' && isRequestKey((value as { key?: unknown }).key)
 
/**
 * Whether an answer is a request's image(s) or file(s): from the field's type,
 * or, for an approver who can't read the membership entity, from its shape
 */
function uploadKind(field: EntityField | undefined, value: unknown): 'image' | 'file' | null {
  const type = field?.type as string | undefined
  if (type === 'image' || type === 'image_set') return 'image'
  if (type === 'file' || type === 'file_set') return 'file'
  if (field) return null
  const entries = Array.isArray(value) ? value : [value]
  if (entries.length && entries.every(isRequestKey)) return 'image'
  if (entries.length && entries.every(isRequestFile)) return 'file'
  return null
}
 
function answerRows(answers: Record<string, unknown>) {
  return Object.entries(answers).map(([fieldId, value]) => {
    const field = fieldsById.value.get(fieldId)
    const upload = uploadKind(field, value)
    const isSet = Array.isArray(value)
    return {
      fieldId,
      label: field ? getTranslation(field.name) : fieldId,
      value: upload ? '' : formatValue(value),
      upload,
      raw: value,
      // The display components only need the type and the id
      field: (field ?? {
        fieldId,
        name: fieldId,
        type: upload === 'image' ? (isSet ? 'image_set' : 'image') : isSet ? 'file_set' : 'file'
      }) as EntityField
    }
  })
}
 
function formatDate(iso?: string): string {
  return iso ? new Date(iso).toLocaleDateString() : ''
}
 
function removeFromList(userId: string) {
  requests.value = requests.value.filter((request) => request.userId !== userId)
}
 
function openApprove(request: MembershipRequest) {
  approving.value = request
  const defaultRole = props.join?.defaultRoleId
  approveRoles.value =
    defaultRole && approvalRoles.value.some((r) => r.roleId === defaultRole) ? [defaultRole] : []
  approveError.value = ''
}
 
function approveErrorMessage(err: any): string {
  const data = err.response?.data ?? {}
  if (data.error === 'ANSWERS_NO_LONGER_VALID') {
    const field = fieldsById.value.get(data.fieldId)
    return t('member.approveAnswersInvalid').replace(
      '{field}',
      field ? getTranslation(field.name) : data.fieldId || ''
    )
  }
  if (data.error === 'INSUFFICIENT_CREDITS') return t('member.approveNoCredits')
  if (data.error === 'ITEM_MODIFIED') return t('member.approveItemModified')
  if (data.error === 'MEMBERSHIP_ENTITY_NOT_SET') return t('member.approveNoEntity')
  return t('member.decisionError')
}
 
async function approve() {
  const request = approving.value
  Iif (!request) return
  if (approveRoles.value.length === 0) {
    approveError.value = t('member.approveNeedsRole')
    return
  }
  approveLoading.value = true
  approveError.value = ''
  try {
    await decideMembershipRequest(props.flowId, request.userId, 'approve', approveRoles.value)
    approving.value = null
    removeFromList(request.userId)
    toastStore.success(t('member.approved').replace('{name}', request.name || request.userId))
    emit('approved')
  } catch (err: any) {
    approveError.value = approveErrorMessage(err)
  } finally {
    approveLoading.value = false
  }
}
 
async function decide(
  request: MembershipRequest,
  decision: Exclude<MembershipDecision, 'approve'>
) {
  busyUserId.value = request.userId
  try {
    await decideMembershipRequest(props.flowId, request.userId, decision)
    removeFromList(request.userId)
    const key = { refuse: 'member.refused', ban: 'member.banned', unban: 'member.unbanned' }[
      decision
    ]
    toastStore.success(t(key).replace('{name}', request.name || request.userId))
  } catch (err: any) {
    // Already decided by someone else: the list was out of date
    if (err.response?.status === 404) removeFromList(request.userId)
    toastStore.error(t('member.decisionError'))
  } finally {
    busyUserId.value = null
  }
}
 
async function banConfirmed() {
  const request = confirmBan.request
  confirmBan.request = null
  Eif (request) await decide(request, 'ban')
}
 
defineExpose({ reload: () => load() })
</script>
 
<style scoped>
.request-answers {
  display: grid;
  grid-template-columns: max-content 1fr;
  column-gap: 0.75rem;
  row-gap: 0.125rem;
}
 
.request-answers dt {
  font-weight: 600;
}
 
.request-answers dd {
  margin: 0;
  overflow-wrap: anywhere;
  white-space: pre-line;
}
 
.request-images {
  max-width: 10rem;
}
 
.min-w-0 {
  min-width: 0;
}
</style>