All files / app/assets/javascripts/invite_members/components invite_members_modal.vue

94.11% Statements 80/85
89.28% Branches 25/28
93.47% Functions 43/46
94.04% Lines 79/84

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                                                  4x                                                                                                                                                                         57x                             63x     63x     57x     63x     102x     111x     11x             57x     57x     3x     11x 21x       11x     11x     11x     6x 1x     5x         67x             39x 3x     36x         57x                   6x     34x         34x           417x 417x   417x 417x     16x     1x 1x 1x     34x   34x 34x   34x                     35x 35x   35x 1x 1x     34x       34x 34x 34x   28x   28x 9x   19x       6x   34x       9x 1x   8x 8x         21x     4x     3x     6x 6x 6x 6x     19x   19x     16x       16x 15x     16x     42x 42x     36x 36x     4x 4x     2x                                                                                                                                                                                                                                                                    
<script>
import { GlAlert, GlButton, GlCollapse, GlIcon } from '@gitlab/ui';
import { partition, isString, uniqueId, isEmpty } from 'lodash';
import SafeHtml from '~/vue_shared/directives/safe_html';
import InviteModalBase from 'ee_else_ce/invite_members/components/invite_modal_base.vue';
import Api from '~/api';
import Tracking from '~/tracking';
import { BV_SHOW_MODAL, BV_HIDE_MODAL } from '~/lib/utils/constants';
import { n__, sprintf } from '~/locale';
import { memberName, triggerExternalAlert } from 'ee_else_ce/invite_members/utils/member_utils';
import { captureException } from '~/ci/runner/sentry_utils';
import {
  USERS_FILTER_ALL,
  MEMBER_MODAL_LABELS,
  INVITE_MEMBER_MODAL_TRACKING_CATEGORY,
} from '../constants';
import eventHub from '../event_hub';
import { responseFromSuccess } from '../utils/response_message_parser';
import { getInvalidFeedbackMessage } from '../utils/get_invalid_feedback_message';
import {
  displaySuccessfulInvitationAlert,
  reloadOnInvitationSuccess,
} from '../utils/trigger_successful_invite_alert';
import ModalConfetti from './confetti.vue';
import MembersTokenSelect from './members_token_select.vue';
import UserLimitNotification from './user_limit_notification.vue';
 
export default {
  name: 'InviteMembersModal',
  components: {
    GlAlert,
    GlButton,
    GlCollapse,
    GlIcon,
    InviteModalBase,
    MembersTokenSelect,
    ModalConfetti,
    UserLimitNotification,
    ActiveTrialNotification: () =>
      import('ee_component/invite_members/components/active_trial_notification.vue'),
  },
  directives: {
    SafeHtml,
  },
  mixins: [Tracking.mixin({ category: INVITE_MEMBER_MODAL_TRACKING_CATEGORY })],
  props: {
    id: {
      type: String,
      required: true,
    },
    rootId: {
      type: String,
      required: true,
    },
    isProject: {
      type: Boolean,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    accessLevels: {
      type: Object,
      required: true,
    },
    defaultAccessLevel: {
      type: Number,
      required: true,
    },
    defaultMemberRoleId: {
      type: Number,
      required: false,
      default: null,
    },
    helpLink: {
      type: String,
      required: true,
    },
    usersFilter: {
      type: String,
      required: false,
      default: USERS_FILTER_ALL,
    },
    filterId: {
      type: Number,
      required: false,
      default: null,
    },
    fullPath: {
      type: String,
      required: true,
    },
    usersLimitDataset: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    activeTrialDataset: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    reloadPageOnSubmit: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      invalidFeedbackMessage: '',
      isLoading: false,
      modalId: uniqueId('invite-members-modal-'),
      newUsersToInvite: [],
      invalidMembers: {},
      source: 'unknown',
      mode: 'default',
      errorsLimit: 2,
      isErrorsSectionExpanded: false,
      shouldShowEmptyInvitesAlert: false,
    };
  },
  computed: {
    isCelebration() {
      return this.mode === 'celebrate';
    },
    modalTitle() {
      return this.$options.labels.modal[this.mode].title;
    },
    inviteTo() {
      return this.isProject ? 'toProject' : 'toGroup';
    },
    labelIntroText() {
      return this.$options.labels[this.inviteTo][this.mode].introText;
    },
    isEmptyInvites() {
      return Boolean(this.newUsersToInvite.length);
    },
    hasInvalidMembers() {
      return !isEmpty(this.invalidMembers);
    },
    memberErrorTitle() {
      return n__(
        "InviteMembersModal|The following member couldn't be invited",
        "InviteMembersModal|The following %d members couldn't be invited",
        this.errorList.length,
      );
    },
    showUserLimitNotification() {
      return !isEmpty(this.usersLimitDataset.alertVariant);
    },
    staticRoles() {
      return { validRoles: this.accessLevels };
    },
    limitVariant() {
      return this.usersLimitDataset.alertVariant;
    },
    errorList() {
      return Object.entries(this.invalidMembers).map(([member, error]) => {
        return { member, displayedMemberName: this.tokenName(member), message: error };
      });
    },
    errorsLimited() {
      return this.errorList.slice(0, this.errorsLimit);
    },
    errorsExpanded() {
      return this.errorList.slice(this.errorsLimit);
    },
    shouldErrorsSectionExpand() {
      return Boolean(this.errorsExpanded.length);
    },
    errorCollapseText() {
      if (this.isErrorsSectionExpanded) {
        return this.$options.labels.expandedErrors;
      }
 
      return sprintf(this.$options.labels.collapsedErrors, {
        count: this.errorsExpanded.length,
      });
    },
    formGroupDescription() {
      return this.invalidFeedbackMessage ? null : this.$options.labels.placeHolder;
    },
  },
  watch: {
    isEmptyInvites: {
      handler(updatedValue) {
        // nothing to do if the invites are **still** empty and the emptyInvites were never set from submit
        if (!updatedValue && !this.shouldShowEmptyInvitesAlert) {
          return;
        }
 
        this.clearEmptyInviteError();
      },
    },
  },
  mounted() {
    if (this.reloadPageOnSubmit) {
      displaySuccessfulInvitationAlert();
    }
 
    eventHub.$on('openModal', (options) => {
      this.openModal(options);
    });
  },
  methods: {
    showInvalidFeedbackMessage(response) {
      this.invalidFeedbackMessage = getInvalidFeedbackMessage(response);
    },
    partitionNewUsersToInvite() {
      const [usersToInviteByEmail, usersToAddById] = partition(
        this.newUsersToInvite,
        (user) => isString(user.id) && user.id.includes('user-defined-token'),
      );
 
      return [
        usersToInviteByEmail.map((user) => user.name).join(','),
        usersToAddById.map((user) => user.id).join(','),
      ];
    },
    openModal({ mode = 'default', source = 'unknown' }) {
      this.mode = mode;
      this.source = source;
 
      this.$root.$emit(BV_SHOW_MODAL, this.modalId);
      this.track('render', { label: this.source });
    },
    closeModal() {
      this.$root.$emit(BV_HIDE_MODAL, this.modalId);
    },
    showEmptyInvitesAlert() {
      this.invalidFeedbackMessage = this.$options.labels.placeHolder;
      this.shouldShowEmptyInvitesAlert = true;
      this.$refs.alerts.focus();
    },
    getInvitePayload({ accessLevel, expiresAt, memberRoleId }) {
      const [usersToInviteByEmail, usersToAddById] = this.partitionNewUsersToInvite();
 
      const email = usersToInviteByEmail !== '' ? { email: usersToInviteByEmail } : {};
      const userId = usersToAddById !== '' ? { user_id: usersToAddById } : {};
 
      return {
        format: 'json',
        expires_at: expiresAt,
        access_level: accessLevel,
        member_role_id: memberRoleId,
        invite_source: this.source,
        ...email,
        ...userId,
      };
    },
    async sendInvite({ accessLevel, expiresAt, memberRoleId }) {
      this.isLoading = true;
      this.clearValidation();
 
      if (!this.isEmptyInvites) {
        this.showEmptyInvitesAlert();
        return;
      }
 
      const apiAddByInvite = this.isProject
        ? Api.inviteProjectMembers.bind(Api)
        : Api.inviteGroupMembers.bind(Api);
 
      try {
        const payload = this.getInvitePayload({ accessLevel, expiresAt, memberRoleId });
        const response = await apiAddByInvite(this.id, payload);
 
        const { error, message } = responseFromSuccess(response);
 
        if (error) {
          this.showErrors(message);
        } else {
          this.onInviteSuccess();
        }
      } catch (error) {
        captureException({ error, component: this.$options.name });
        this.showInvalidFeedbackMessage(error);
      } finally {
        this.isLoading = false;
      }
    },
    showErrors(message) {
      if (isString(message)) {
        this.invalidFeedbackMessage = message;
      } else {
        this.invalidMembers = message;
        this.$refs.alerts.focus();
      }
    },
    tokenName(username) {
      // initial token creation hits this and nothing is found... so safe navigation
      return this.newUsersToInvite.find((member) => memberName(member) === username)?.name;
    },
    onCancel() {
      this.track('click_cancel', { label: this.source });
    },
    onClose() {
      this.track('click_x', { label: this.source });
    },
    resetFields() {
      this.clearValidation();
      this.isLoading = false;
      this.shouldShowEmptyInvitesAlert = false;
      this.newUsersToInvite = [];
    },
    onInviteSuccess() {
      this.track('invite_successful', { label: this.source });
 
      if (this.reloadPageOnSubmit) {
        reloadOnInvitationSuccess();
      } else {
        this.showSuccessMessage();
      }
    },
    showSuccessMessage() {
      if (!triggerExternalAlert(this.source)) {
        this.$toast.show(this.$options.labels.toastMessageSuccessful);
      }
 
      this.closeModal();
    },
    clearValidation() {
      this.invalidFeedbackMessage = '';
      this.invalidMembers = {};
    },
    clearEmptyInviteError() {
      this.invalidFeedbackMessage = '';
      this.shouldShowEmptyInvitesAlert = false;
    },
    removeToken(token) {
      delete this.invalidMembers[memberName(token)];
      this.invalidMembers = { ...this.invalidMembers };
    },
    toggleErrorExpansion() {
      this.isErrorsSectionExpanded = !this.isErrorsSectionExpanded;
    },
  },
  labels: MEMBER_MODAL_LABELS,
};
</script>
<template>
  <invite-modal-base
    :modal-id="modalId"
    :modal-title="modalTitle"
    :name="name"
    :access-levels="staticRoles"
    :default-access-level="defaultAccessLevel"
    :default-member-role-id="defaultMemberRoleId"
    :help-link="helpLink"
    :label-intro-text="labelIntroText"
    :label-search-field="$options.labels.searchField"
    :form-group-description="formGroupDescription"
    :invalid-feedback-message="invalidFeedbackMessage"
    :is-loading="isLoading"
    :is-project="isProject"
    :new-users-to-invite="newUsersToInvite"
    :root-group-id="rootId"
    :users-limit-dataset="usersLimitDataset"
    :full-path="fullPath"
    @close="onClose"
    @cancel="onCancel"
    @reset="resetFields"
    @submit="sendInvite"
  >
    <template #intro-text-before>
      <div v-if="isCelebration" class="gl-p-4 gl-font-size-h1">
        <gl-emoji data-name="tada" />
      </div>
    </template>
    <template #intro-text-after>
      <br />
      <span v-if="isCelebration">{{ $options.labels.modal.celebrate.intro }} </span>
      <modal-confetti v-if="isCelebration" />
    </template>
 
    <template #alert>
      <div ref="alerts" tabindex="-1">
        <gl-alert
          v-if="shouldShowEmptyInvitesAlert"
          id="empty-invites-alert"
          class="gl-mb-4"
          variant="danger"
          :dismissible="false"
          data-testid="empty-invites-alert"
        >
          {{ $options.labels.emptyInvitesAlertText }}
        </gl-alert>
        <gl-alert
          v-if="hasInvalidMembers"
          class="gl-mb-4"
          variant="danger"
          :dismissible="false"
          :title="memberErrorTitle"
          data-testid="alert-member-error"
        >
          {{ $options.labels.memberErrorListText }}
          <ul class="gl-pl-5 gl-mb-0">
            <li
              v-for="error in errorsLimited"
              :key="error.member"
              data-testid="errors-limited-item"
            >
              <strong>{{ error.displayedMemberName }}:</strong>
              <span v-safe-html="error.message"></span>
            </li>
          </ul>
          <template v-if="shouldErrorsSectionExpand">
            <gl-collapse v-model="isErrorsSectionExpanded">
              <ul class="gl-pl-5 gl-mb-0">
                <li
                  v-for="error in errorsExpanded"
                  :key="error.member"
                  data-testid="errors-expanded-item"
                >
                  <strong>{{ error.displayedMemberName }}:</strong>
                  <span v-safe-html="error.message"></span>
                </li>
              </ul>
            </gl-collapse>
            <gl-button
              class="gl-text-decoration-none! gl-shadow-none! gl-mt-3"
              data-testid="accordion-button"
              variant="link"
              @click="toggleErrorExpansion"
            >
              {{ errorCollapseText }}
              <gl-icon
                name="chevron-down"
                class="gl-transition-medium"
                :class="{ 'gl-rotate-180': isErrorsSectionExpanded }"
              />
            </gl-button>
          </template>
        </gl-alert>
        <user-limit-notification
          v-else-if="showUserLimitNotification"
          class="gl-mb-5"
          :limit-variant="limitVariant"
          :users-limit-dataset="usersLimitDataset"
        />
      </div>
    </template>
 
    <template #active-trial-alert>
      <active-trial-notification v-if="!isCelebration" :active-trial-dataset="activeTrialDataset" />
    </template>
 
    <template #select="{ exceptionState, inputId }">
      <members-token-select
        v-model="newUsersToInvite"
        class="gl-mb-2"
        aria-labelledby="empty-invites-alert"
        :input-id="inputId"
        :exception-state="exceptionState"
        :users-filter="usersFilter"
        :filter-id="filterId"
        :group-id="id"
        :invalid-members="invalidMembers"
        @clear="clearValidation"
        @token-remove="removeToken"
      />
    </template>
  </invite-modal-base>
</template>