All files / app/assets/javascripts/protected_branches protected_branch_edit.js

89.33% Statements 67/75
68% Branches 17/25
100% Functions 23/23
91.17% Lines 62/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                1x 26x         22x   22x 22x   22x       22x   22x       12x   12x 12x 12x 3x 3x 3x         2x 2x           12x 11x 11x 11x 3x 3x 3x         2x 2x                   10x               10x                 20x 20x   18x 18x                       18x 18x   18x 18x       18x 2x   16x 2x 2x             4x 4x       5x 4x       10x           2x         4x 8x 8x   4x 4x 4x 8x           8x 4x                                   4x                 4x               8x 8x 6x 6x        
import { find } from 'lodash';
import { createAlert } from '~/alert';
import axios from '~/lib/utils/axios_utils';
import { __ } from '~/locale';
import { initToggle } from '~/toggles';
import { initAccessDropdown } from '~/projects/settings/init_access_dropdown';
import { ACCESS_LEVELS, LEVEL_TYPES } from './constants';
 
const isDropdownDisabled = (dropdown) => {
  return dropdown?.$options.disabled === '';
};
 
export default class ProtectedBranchEdit {
  constructor(options) {
    this.hasLicense = options.hasLicense;
 
    this.hasChanges = false;
    this.$wrap = options.$wrap;
 
    this.selectedItems = {
      [ACCESS_LEVELS.PUSH]: [],
      [ACCESS_LEVELS.MERGE]: [],
    };
    this.initDropdowns();
 
    this.initToggles();
  }
 
  initToggles() {
    const wrap = this.$wrap.get(0);
 
    const forcePushToggle = initToggle(wrap.querySelector('.js-force-push-toggle'));
    Eif (forcePushToggle) {
      forcePushToggle.$on('change', (value) => {
        forcePushToggle.isLoading = true;
        forcePushToggle.disabled = true;
        this.updateProtectedBranch(
          {
            allow_force_push: value,
          },
          () => {
            forcePushToggle.isLoading = false;
            forcePushToggle.disabled = false;
          },
        );
      });
    }
 
    if (this.hasLicense) {
      const codeOwnerToggle = initToggle(wrap.querySelector('.js-code-owner-toggle'));
      Eif (codeOwnerToggle) {
        codeOwnerToggle.$on('change', (value) => {
          codeOwnerToggle.isLoading = true;
          codeOwnerToggle.disabled = true;
          this.updateProtectedBranch(
            {
              code_owner_approval_required: value,
            },
            () => {
              codeOwnerToggle.isLoading = false;
              codeOwnerToggle.disabled = false;
            },
          );
        });
      }
    }
  }
 
  initDropdowns() {
    // Allowed to Merge dropdown
    this[`${ACCESS_LEVELS.MERGE}_dropdown`] = this.buildDropdown(
      'js-allowed-to-merge',
      ACCESS_LEVELS.MERGE,
      gon.merge_access_levels,
      'protected-branch-allowed-to-merge',
    );
 
    // Allowed to Push dropdown
    this[`${ACCESS_LEVELS.PUSH}_dropdown`] = this.buildDropdown(
      'js-allowed-to-push',
      ACCESS_LEVELS.PUSH,
      gon.push_access_levels,
      'protected-branch-allowed-to-push',
    );
  }
 
  buildDropdown(selector, accessLevel, accessLevelsData, testId) {
    const [el] = this.$wrap.find(`.${selector}`);
    if (!el) return undefined;
 
    const projectId = gon.current_project_id;
    const dropdown = initAccessDropdown(el, {
      toggleClass: selector,
      hasLicense: this.hasLicense,
      searchEnabled: el.dataset.filter !== undefined,
      showUsers: projectId !== undefined,
      block: true,
      accessLevel,
      accessLevelsData,
      groupsWithProjectAccess: true,
      testId,
    });
 
    dropdown.$on('select', (selected) => this.onSelectItems(accessLevel, selected));
    dropdown.$on('hidden', () => this.onDropdownHide());
 
    this.initSelectedItems(dropdown, accessLevel);
    return dropdown;
  }
 
  initSelectedItems(dropdown, accessLevel) {
    if (isDropdownDisabled(dropdown)) {
      return;
    }
    this.selectedItems[accessLevel] = dropdown.preselected.map((item) => {
      Iif (item.type === LEVEL_TYPES.USER) return { id: item.id, user_id: item.user_id };
      Eif (item.type === LEVEL_TYPES.ROLE) return { id: item.id, access_level: item.access_level };
      if (item.type === LEVEL_TYPES.GROUP) return { id: item.id, group_id: item.group_id };
      return { id: item.id, deploy_key_id: item.deploy_key_id };
    });
  }
 
  onSelectItems(accessLevel, selected) {
    this.selectedItems[accessLevel] = selected;
    this.hasChanges = true;
  }
 
  onDropdownHide() {
    if (!this.hasChanges) return;
    this.updatePermissions();
  }
 
  updateProtectedBranch(formData, callback) {
    axios
      .patch(this.$wrap.data('url'), {
        protected_branch: formData,
      })
      .then(callback)
      .catch(() => {
        createAlert({ message: __('Failed to update branch!') });
      });
  }
 
  updatePermissions() {
    const formData = Object.values(ACCESS_LEVELS).reduce((acc, level) => {
      acc[`${level}_attributes`] = this.selectedItems[level];
      return acc;
    }, {});
    this.updateProtectedBranch(formData, ({ data }) => {
      this.hasChanges = false;
      Object.values(ACCESS_LEVELS).forEach((level) => {
        this.setSelectedItemsToDropdown(data[level], level);
      });
    });
  }
 
  setSelectedItemsToDropdown(items = [], accessLevel) {
    const itemsToAdd = items.map((currentItem) => {
      Iif (currentItem.user_id) {
        // Do this only for users for now
        // get the current data for selected items
        const selectedItems = this.selectedItems[accessLevel];
        const currentSelectedItem = find(selectedItems, {
          user_id: currentItem.user_id,
        });
 
        return {
          id: currentItem.id,
          user_id: currentItem.user_id,
          type: LEVEL_TYPES.USER,
          persisted: true,
          name: currentSelectedItem.name,
          username: currentSelectedItem.username,
          avatar_url: currentSelectedItem.avatar_url,
        };
      }
      Iif (currentItem.group_id) {
        return {
          id: currentItem.id,
          group_id: currentItem.group_id,
          type: LEVEL_TYPES.GROUP,
          persisted: true,
        };
      }
 
      return {
        id: currentItem.id,
        access_level: currentItem.access_level,
        type: LEVEL_TYPES.ROLE,
        persisted: true,
      };
    });
 
    const dropdown = this[`${accessLevel}_dropdown`];
    if (!isDropdownDisabled(dropdown)) {
      this.selectedItems[accessLevel] = itemsToAdd;
      dropdown?.setPreselectedItems(itemsToAdd);
    }
  }
}