All files / modules/20-rbac/pages/UserDetails/views UserGroupTable.tsx

93.51% Statements 72/77
53.03% Branches 35/66
90% Functions 18/20
93.33% Lines 70/75

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              10x 10x   10x                     10x 10x 10x 10x 10x   10x 10x                 10x 10x 10x 10x 10x   10x 10x   10x 5x 5x                 10x 10x 10x 10x 10x 10x 10x 10x               10x               1x 1x 1x     1x 1x         1x               10x 1x 1x 1x     10x       2x                   1x 1x                                                                           10x   5x 5x 5x 5x           5x                 5x               5x 1x           5x 1x         1x         1x 1x 1x   1x     1x             5x   2x 1x         5x 3x     3x               3x                       5x                                                                 1x                 10x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 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/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import type { CellProps, Column, Renderer } from 'react-table'
import {
  Layout,
  Text,
  Button,
  Container,
  PageError,
  TableV2,
  useConfirmationDialog,
  ButtonVariation,
  Card
} from '@wings-software/uicore'
import { Color, FontVariation, Intent } from '@harness/design-system'
import { Classes, Menu, Popover, Position, PopoverInteractionKind } from '@blueprintjs/core'
import { defaultTo } from 'lodash-es'
import { useToaster } from '@common/components'
import { useMutateAsGet } from '@common/hooks'
import type { PipelineType, ProjectPathProps, UserPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import {
  AddUsers,
  ResponseListUserGroupDTO,
  useAddUsers,
  useGetBatchUserGroupList,
  UserAggregate,
  useRemoveMember,
  UserGroupDTO
} from 'services/cd-ng'
import ManagePrincipalButton from '@rbac/components/ManagePrincipalButton/ManagePrincipalButton'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import useSelectUserGroupsModal from '@common/modals/SelectUserGroups/useSelectUserGroupsModal'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
import type { ScopeAndIdentifier } from '@common/components/MultiSelectEntityReference/MultiSelectEntityReference'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from '@rbac/pages/UserDetails/UserDetails.module.scss'
 
const RenderColumnDetails: Renderer<CellProps<UserGroupDTO>> = ({ row }) => {
  const data = row.original
  return (
    <Layout.Horizontal spacing="small" className={css.name}>
      <Text color={Color.BLACK} lineClamp={1}>
        {data.name}
      </Text>
    </Layout.Horizontal>
  )
}
 
const ResourceGroupColumnMenu: Renderer<CellProps<UserGroupDTO>> = ({ row, column }) => {
  const data = row.original
  const [menuOpen, setMenuOpen] = useState(false)
  const { showSuccess, showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const { getString } = useStrings()
  const { mutate: deleteUserGroup } = useRemoveMember({
    identifier: (column as any).userIdentifier,
    pathParams: {
      identifier: data.identifier || ''
    },
    queryParams: { accountIdentifier: accountId, projectIdentifier, orgIdentifier }
  })
 
  const { openDialog } = useConfirmationDialog({
    contentText: `${getString('rbac.userDetails.userGroup.confirmDeleteText', { name: data.name })}`,
    titleText: getString('rbac.userDetails.userGroup.deleteTitle'),
    confirmButtonText: getString('common.remove'),
    cancelButtonText: getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async (isConfirmed: boolean) => {
      Eif (isConfirmed) {
        try {
          const deleted = await deleteUserGroup((column as any).userIdentifier, {
            headers: { 'content-type': 'application/json' }
          })
          Eif (deleted)
            showSuccess(
              getString('rbac.userDetails.userGroup.deleteSuccessMessage', {
                name: data.name
              })
            )
          ;(column as any).reload?.()
        } catch (err) {
          showError(getRBACErrorMessage(err))
        }
      }
    }
  })
 
  const handleDelete = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    openDialog()
  }
 
  return (
    <Popover
      isOpen={menuOpen}
      onInteraction={nextOpenState => {
        setMenuOpen(nextOpenState)
      }}
      className={Classes.DARK}
      position={Position.RIGHT_TOP}
    >
      <Button
        minimal
        icon="Options"
        data-testid={`menu-UserGroup-${data.name}`}
        onClick={e => {
          e.stopPropagation()
          setMenuOpen(true)
        }}
      />
      <Menu>
        {data.externallyManaged ? (
          <Popover
            position={Position.TOP}
            fill
            usePortal
            inheritDarkTheme={false}
            interactionKind={PopoverInteractionKind.HOVER}
            hoverCloseDelay={50}
            content={
              <div className={css.popover}>
                <Text font={{ variation: FontVariation.SMALL }}>{getString('rbac.unableToEditSCIMMembership')}</Text>
              </div>
            }
          >
            <div
              onClick={(event: React.MouseEvent<HTMLElement, MouseEvent>) => {
                event.stopPropagation()
              }}
            >
              <Menu.Item icon="trash" text={getString('common.remove')} onClick={handleDelete} disabled />
            </div>
          </Popover>
        ) : (
          <Menu.Item icon="trash" text={getString('common.remove')} onClick={handleDelete} />
        )}
      </Menu>
    </Popover>
  )
}
 
interface UserGroupTableProps {
  user: UserAggregate
}
 
const UserGroupTable: React.FC<UserGroupTableProps> = ({ user }) => {
  const { accountId, orgIdentifier, projectIdentifier, userIdentifier } =
    useParams<PipelineType<ProjectPathProps & UserPathProps>>()
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const { showSuccess, showError } = useToaster()
  const {
    data: userGroupData,
    loading,
    error,
    refetch
  } = useMutateAsGet(useGetBatchUserGroupList, {
    body: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      userIdentifierFilter: [userIdentifier]
    }
  })
 
  const { mutate: addUserToGroups, loading: sending } = useAddUsers({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier: orgIdentifier,
      projectIdentifier: projectIdentifier
    }
  })
 
  const getUserGroupScopeAndID = (groups: ResponseListUserGroupDTO | null): ScopeAndIdentifier[] | undefined => {
    return groups?.data?.map(value => ({
      identifier: value.identifier,
      scope: getScopeFromDTO(value)
    }))
  }
 
  const addUserToUserGroups = async (userGroups: string[]): Promise<void> => {
    const dataToSubmit: AddUsers = {
      emails: [user.user.email],
      roleBindings: user.roleAssignmentMetadata,
      userGroups: userGroups.concat(
        defaultTo(
          userGroupData?.data?.map(value => value.identifier),
          []
        )
      )
    }
    try {
      await addUserToGroups(dataToSubmit)
      showSuccess(
        getString('rbac.userDetails.userGroup.addSuccessMessage', {
          Groups: userGroupData?.data?.map(value => value.name).join(', ')
        })
      )
      refetch()
    } catch (e) {
      showError(getRBACErrorMessage(e))
      openSelectUserGroupsModal(getUserGroupScopeAndID(userGroupData))
    }
  }
 
  const { openSelectUserGroupsModal } = useSelectUserGroupsModal({
    onSuccess: data => {
      const userGroups = data.map(value => value.identifier)
      addUserToUserGroups(userGroups)
    },
    onlyCurrentScope: true,
    disablePreSelectedItems: true
  })
  const columns: Column<UserGroupDTO>[] = useMemo(
    () => [
      {
        Header: '',
        accessor: row => row.name,
        id: 'name',
        width: '95%',
        disableSortBy: true,
        Cell: RenderColumnDetails
      },
      {
        Header: '',
        accessor: row => row.identifier,
        width: '5%',
        id: 'action',
        Cell: ResourceGroupColumnMenu,
        disableSortBy: true,
        reload: refetch,
        userIdentifier
      }
    ],
    []
  )
 
  return (
    <Container margin={{ bottom: 'medium' }}>
      <Text color={Color.BLACK} font={{ size: 'medium', weight: 'semi-bold' }} padding={{ bottom: 'medium' }}>
        {getString('common.userGroups')}
      </Text>
 
      <Layout.Vertical padding={{ bottom: 'medium' }}>
        {error ? (
          <PageError message={(error?.data as Error)?.message || error?.message} onClick={() => refetch()} />
        ) : loading ? (
          <ContainerSpinner />
        ) : userGroupData?.data?.length ? (
          <TableV2<UserGroupDTO>
            hideHeaders={true}
            data={userGroupData.data}
            columns={columns}
            className={css.userGroupTable}
          />
        ) : (
          <Card>{getString('rbac.userGroupPage.noUserGroups')}</Card>
        )}
      </Layout.Vertical>
 
      <ManagePrincipalButton
        data-testid={'add-UserGroup'}
        text={
          sending
            ? getString('rbac.userDetails.userGroup.addingToGroups')
            : getString('common.plusNumber', { number: getString('rbac.userDetails.userGroup.addToGroup') })
        }
        disabled={sending}
        variation={ButtonVariation.LINK}
        onClick={() => {
          openSelectUserGroupsModal(getUserGroupScopeAndID(userGroupData))
        }}
        resourceIdentifier={userIdentifier}
        resourceType={ResourceType.USER}
      />
    </Container>
  )
}
 
export default UserGroupTable