All files / modules/20-rbac/modals/RoleAssignmentModal/views RoleAssignmentForm.tsx

73.58% Statements 39/53
60.42% Branches 29/48
81.82% Functions 9/11
74.51% Lines 38/51

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              26x 26x 26x   26x 26x 26x   26x 26x 26x 26x 26x 26x 26x     26x   26x 26x 26x                 26x 33x 33x 33x 33x 33x 33x   33x             33x       33x       33x   5x 15x                   33x   12x             33x                                     33x             65x                               65x                               65x                                                           26x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Free Trial 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/05/PolyForm-Free-Trial-1.0.0.txt.
 */
 
import React, { useMemo } from 'react'
import { Container, Layout, Text, FieldArray, Select, SelectOption } from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import type { FormikProps } from 'formik'
import { defaultTo } from 'lodash-es'
import { useDeleteRoleAssignment, useGetRoleList } from 'services/rbac'
import { useStrings } from 'framework/strings'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useGetResourceGroupListV2 } from 'services/resourcegroups'
import { errorCheck } from '@common/utils/formikHelpers'
import { useToaster } from '@common/components'
import { getScopeBasedDefaultResourceGroup, isAssignmentFieldDisabled } from '@rbac/utils/utils'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import NewUserRoleDropdown from '@rbac/components/NewUserRoleDropdown/NewUserRoleDropdown'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { Assignment, RoleOption, UserRoleAssignmentValues } from './UserRoleAssigment'
import type { RoleAssignmentValues } from './RoleAssignment'
import css from './RoleAssignmentForm.module.scss'
 
export enum InviteType {
  ADMIN_INITIATED = 'ADMIN_INITIATED_INVITE',
  USER_INITIATED = 'USER_INITIATED_INVITE'
}
 
interface RoleAssignmentFormProps {
  noRoleAssignmentsText: string
  formik: FormikProps<UserRoleAssignmentValues | RoleAssignmentValues>
  onSuccess?: () => void
}
 
const RoleAssignmentForm: React.FC<RoleAssignmentFormProps> = ({ noRoleAssignmentsText, formik, onSuccess }) => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const scope = getScopeFromDTO({ accountIdentifier: accountId, orgIdentifier, projectIdentifier })
  const { showSuccess, showError } = useToaster()
  const defaultResourceGroup = getScopeBasedDefaultResourceGroup(scope, getString)
 
  const { mutate: deleteRoleAssignment } = useDeleteRoleAssignment({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
  const { data: roleList } = useGetRoleList({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier }
  })
 
  const { data: resourceGroupList } = useGetResourceGroupListV2({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier }
  })
 
  const roles: RoleOption[] = useMemo(
    () =>
      roleList?.data?.content?.map(response => {
        return {
          label: response.role.name,
          value: response.role.identifier,
          managed: defaultTo(response.harnessManaged, false),
          managedRoleAssignment: false
        }
      }) || [],
    [roleList]
  )
 
  const resourceGroups: SelectOption[] = useMemo(
    () =>
      resourceGroupList?.data?.content?.map(response => ({
        label: defaultTo(response.resourceGroup.name, ''),
        value: defaultTo(response.resourceGroup.identifier, '')
      })) || [],
    [resourceGroupList]
  )
 
  const handleRoleAssignmentDelete = async (identifier: string): Promise<boolean> => {
    try {
      const deleted = await deleteRoleAssignment(identifier, {
        headers: { 'content-type': 'application/json' }
      })
      if (deleted) {
        showSuccess(getString('rbac.roleAssignment.deleteSuccess'))
        onSuccess?.()
        return true
      } else {
        showError(getString('rbac.roleAssignment.deleteFailure'))
      }
    } catch (err) {
      /* istanbul ignore next */
      showError(getRBACErrorMessage(err))
    }
    return false
  }
 
  return (
    <Container className={css.roleAssignments}>
      <FieldArray
        label={getString('rbac.usersPage.assignRoleBindings')}
        name="assignments"
        placeholder={noRoleAssignmentsText}
        insertRowAtBeginning={false}
        isDeleteOfRowAllowed={row => !(row as Assignment).role.managedRoleAssignment}
        onDeleteOfRow={async row => {
          const assignment = (row as Assignment).role.assignmentIdentifier
          if (assignment) {
            const deleted = await handleRoleAssignmentDelete(assignment)
            if (!deleted) return false
          }
          return true
        }}
        containerProps={{ className: css.containerProps }}
        fields={[
          {
            name: 'role',
            label: getString('roles'),
            // eslint-disable-next-line react/display-name
            renderer: (value, _index, handleChange, error) => (
              <Layout.Vertical flex={{ alignItems: 'end' }} spacing="xsmall">
                <NewUserRoleDropdown value={value} handleChange={handleChange} roles={roles} />
                {errorCheck('assignments', formik) && error ? (
                  <Text intent="danger" font="xsmall">
                    {getString('rbac.usersPage.validation.role')}
                  </Text>
                ) : null}
              </Layout.Vertical>
            )
          },
          {
            name: 'resourceGroup',
            label: getString('resourceGroups'),
            defaultValue: defaultResourceGroup,
            // eslint-disable-next-line react/display-name
            renderer: (value, _index, handleChange, error) => {
              return (
                <Layout.Vertical flex={{ alignItems: 'end' }} spacing="xsmall">
                  <Select
                    items={resourceGroups}
                    value={value}
                    disabled={isAssignmentFieldDisabled(value)}
                    popoverClassName={css.selectPopover}
                    inputProps={{
                      placeholder: getString('rbac.usersPage.selectResourceGroup'),
                      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                      // @ts-ignore
                      'data-testid': `resourceGroup-${_index}`
                    }}
                    onChange={handleChange}
                  />
                  {errorCheck('assignments', formik) && error ? (
                    <Text intent="danger" font="xsmall">
                      {getString('rbac.usersPage.validation.resourceGroup')}
                    </Text>
                  ) : null}
                </Layout.Vertical>
              )
            }
          }
        ]}
      />
    </Container>
  )
}
 
export default RoleAssignmentForm