All files / src/components FlowSpaceJoinSettings.vue

97.46% Statements 77/79
92.59% Branches 75/81
100% Functions 33/33
100% Lines 68/68

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  52x 5x       5x                     5x                 2x               5x                   1x     30x                         5x                       2x   5x     5x                   3x   5x 28x       5x       5x                   1x     13x                                     2x   5x 15x                                                   5x                                   16x                 16x   16x 16x   16x 16x 16x 16x   18x 21x 29x     21x     32x                 17x 17x 17x 17x           1x 1x   17x       16x 17x     16x 20x 29x   20x 13x                     13x     16x 7x             9x 31x         6x 6x         2x                 3x 3x 3x 1x 1x   3x 6x   3x                       2x 2x      
<template>
  <div class="space-join-settings border-top pt-3 mt-3" data-testid="space-join-settings">
    <h3 class="fs-6 fw-semibold">
      <font-awesome-icon icon="user-plus" class="me-1" />
      {{ t('space.joinTitle') }}
    </h3>
    <p class="small text-muted mb-2">{{ t('space.joinHelp') }}</p>
 
    <div v-if="loading" class="small text-muted" data-testid="space-join-loading">
      <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>
      {{ t('common.loading') }}
    </div>
    <div v-else-if="loadError" class="small text-danger" data-testid="space-join-load-error">
      {{ t('space.joinLoadError') }}
    </div>
 
    <template v-else>
      <div class="form-check form-switch mb-3">
        <input
          id="space-join-enabled"
          :checked="!!join"
          type="checkbox"
          role="switch"
          class="form-check-input"
          :disabled="disabled"
          data-testid="space-join-enabled"
          @change="toggle(($event.target as HTMLInputElement).checked)"
        />
        <label for="space-join-enabled" class="form-check-label">{{
          t('space.joinEnabled')
        }}</label>
      </div>
 
      <div v-if="join" class="row g-3">
        <div class="col-sm-6">
          <label for="space-join-role" class="form-label small">{{
            t('space.joinDefaultRole')
          }}</label>
          <select
            id="space-join-role"
            :value="join.defaultRoleId"
            class="form-select"
            :disabled="disabled"
            data-testid="space-join-role"
            @change="patch({ defaultRoleId: ($event.target as HTMLSelectElement).value })"
          >
            <option v-if="!join.defaultRoleId" value="" disabled>{{ t('common.select') }}</option>
            <option v-for="role in roles" :key="role.roleId" :value="role.roleId">
              {{ getTranslation(role.name) }}
            </option>
          </select>
          <div
            v-if="!join.defaultRoleId"
            class="small text-warning-emphasis mt-1"
            data-testid="space-join-role-required"
          >
            {{ t('space.joinRoleRequired') }}
          </div>
        </div>
 
        <div class="col-sm-6">
          <label for="space-join-privacy" class="form-label small">{{
            t('space.joinPrivacyContact')
          }}</label>
          <input
            id="space-join-privacy"
            :value="join.privacyContact ?? ''"
            type="email"
            maxlength="254"
            class="form-control"
            :disabled="disabled"
            data-testid="space-join-privacy"
            @input="patch({ privacyContact: ($event.target as HTMLInputElement).value })"
          />
          <div class="small text-muted mt-1">{{ t('space.joinPrivacyContactHelp') }}</div>
        </div>
 
        <div class="col-sm-6">
          <label for="space-join-entity" class="form-label small">{{
            t('space.joinEntity')
          }}</label>
          <select
            id="space-join-entity"
            :value="join.entityId ?? ''"
            class="form-select"
            :disabled="disabled"
            data-testid="space-join-entity"
            @change="selectEntity(($event.target as HTMLSelectElement).value)"
          >
            <option value="">{{ t('space.joinNone') }}</option>
            <option v-for="option in entities" :key="option.id" :value="option.id">
              {{ getTranslation(option.name) }}
            </option>
          </select>
          <div class="small text-muted mt-1">{{ t('space.joinEntityHelp') }}</div>
        </div>
 
        <template v-if="join.entityId">
          <div class="col-sm-6">
            <label for="space-join-user-field" class="form-label small">{{
              t('space.joinUserField')
            }}</label>
            <select
              id="space-join-user-field"
              :value="join.userFieldId ?? ''"
              class="form-select"
              :disabled="disabled"
              data-testid="space-join-user-field"
              @change="patch({ userFieldId: ($event.target as HTMLSelectElement).value })"
            >
              <option v-if="!join.userFieldId" value="" disabled>{{ t('common.select') }}</option>
              <option v-for="field in userFields" :key="field.fieldId" :value="field.fieldId">
                {{ getTranslation(field.name) }}
              </option>
            </select>
            <div v-if="userFields.length === 0" class="small text-warning-emphasis mt-1">
              {{ t('space.joinNoUserField') }}
            </div>
          </div>
 
          <div v-if="formerStateOptions.length > 0" class="col-sm-6">
            <label for="space-join-former-state" class="form-label small">{{
              t('space.joinFormerState')
            }}</label>
            <select
              id="space-join-former-state"
              :value="formerStateValue"
              class="form-select"
              :disabled="disabled"
              data-testid="space-join-former-state"
              @change="selectFormerState(($event.target as HTMLSelectElement).value)"
            >
              <option value="">{{ t('space.joinFormerStateNone') }}</option>
              <option
                v-for="option in formerStateOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </option>
            </select>
          </div>
          <div v-if="formerStateOptions.length > 0" class="col-12 small text-muted">
            {{ t('space.joinFormerStateHelp') }}
          </div>
 
          <div
            v-if="unsupportedField"
            class="col-12 small text-danger"
            data-testid="space-join-unsupported"
          >
            <font-awesome-icon icon="exclamation-triangle" />
            {{
              t('space.joinUnsupportedField').replace(
                '{field}',
                getTranslation(unsupportedField.name)
              )
            }}
          </div>
          <div class="col-12 small text-muted">{{ t('space.joinFieldTypesHint') }}</div>
        </template>
      </div>
    </template>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-SPACE-003.1, UC-SPACE-006.1
import { computed, onMounted, ref, watch } from 'vue'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import { fetchOwnEntitiesOf, fetchRolesOf } from '@/services/membershipRequests'
import { JOIN_FIELD_TYPES, type FlowSpaceJoin } from '@/utils/spaceTheme'
import type { Entity } from '@/stores/entities'
import type { Role } from '@/stores/roles'
 
const props = withDefaults(
  defineProps<{
    modelValue?: FlowSpaceJoin
    flowId: string
    disabled?: boolean
  }>(),
  { modelValue: undefined, disabled: false }
)
 
const emit = defineEmits<{ 'update:modelValue': [value: FlowSpaceJoin | undefined] }>()
 
const { t } = useUILanguage()
const { getTranslation } = useLanguage()
 
const entities = ref<Entity[]>([])
const roles = ref<Role[]>([])
const loading = ref(false)
const loadError = ref(false)
 
const join = computed(() => props.modelValue)
const entity = computed(() => entities.value.find((e) => e.id === join.value?.entityId))
const userFields = computed(() => (entity.value?.fields ?? []).filter((f) => f.type === 'user'))
 
/** A mandatory field the join form can't show: the API would refuse the settings */
const unsupportedField = computed(() =>
  (entity.value?.fields ?? []).find(
    (field) =>
      field.mandatory &&
      !(field as { deprecated?: boolean }).deprecated &&
      field.fieldId !== join.value?.userFieldId &&
      field.type !== 'workflow' &&
      !(JOIN_FIELD_TYPES as readonly string[]).includes(field.type ?? 'text')
  )
)
 
async function load() {
  loading.value = true
  loadError.value = false
  try {
    ;[entities.value, roles.value] = await Promise.all([
      fetchOwnEntitiesOf(props.flowId),
      fetchRolesOf(props.flowId)
    ])
  } catch (err) {
    // Typically 403: listing entities or roles needs entities:list / roles:list
    console.error('[FlowSpaceJoinSettings] failed to load entities or roles:', err)
    loadError.value = true
  } finally {
    loading.value = false
  }
}
 
onMounted(load)
watch(() => props.flowId, load)
 
/** The workflow fields' states, as "fieldId:stateId" options labelled "Field — State" */
const formerStateOptions = computed(() => {
  const workflowFields = (entity.value?.fields ?? []).filter(
    (field) => field.type === 'workflow' && field.workflowDefinition
  )
  return workflowFields.flatMap((field) =>
    (field.workflowDefinition?.states ?? []).map((state) => ({
      value: `${field.fieldId}:${state.id}`,
      label:
        workflowFields.length > 1
          ? `${getTranslation(field.name)} — ${stateLabel(state.label)}`
          : stateLabel(state.label)
    }))
  )
})
 
function stateLabel(label: Record<string, string> | string): string {
  return typeof label === 'string' ? label : getTranslation(label)
}
 
const formerStateValue = computed(() =>
  join.value?.formerMemberFieldId && join.value.formerMemberStateId
    ? `${join.value.formerMemberFieldId}:${join.value.formerMemberStateId}`
    : ''
)
 
/** Without the optional keys set to nothing, so they are not sent */
function withoutEmpty(value: FlowSpaceJoin): FlowSpaceJoin {
  return Object.fromEntries(
    Object.entries(value).filter(([, entry]) => entry !== undefined && entry !== '')
  ) as unknown as FlowSpaceJoin
}
 
function patch(change: Partial<FlowSpaceJoin>) {
  Iif (!join.value) return
  emit('update:modelValue', withoutEmpty({ ...join.value, ...change }))
}
 
/** Turning requests on starts from nothing but the role to choose; off closes joining */
function toggle(enabled: boolean) {
  emit('update:modelValue', enabled ? { defaultRoleId: '' } : undefined)
}
 
/**
 * Choosing an entity pre-selects its only user field; "None" keeps joining
 * open, with no form nor membership item. Either way the former member state
 * of the previous entity is dropped.
 */
function selectEntity(entityId: string) {
  Iif (!join.value) return
  const { defaultRoleId, privacyContact } = join.value
  if (!entityId) {
    emit('update:modelValue', withoutEmpty({ defaultRoleId, privacyContact }))
    return
  }
  const fields = (entities.value.find((e) => e.id === entityId)?.fields ?? []).filter(
    (f) => f.type === 'user'
  )
  emit(
    'update:modelValue',
    withoutEmpty({
      defaultRoleId,
      privacyContact,
      entityId,
      userFieldId: fields.length === 1 ? (fields[0].fieldId ?? '') : ''
    })
  )
}
 
function selectFormerState(value: string) {
  const [fieldId, stateId] = value ? value.split(':') : []
  patch({ formerMemberFieldId: fieldId, formerMemberStateId: stateId })
}
</script>