All files / modules/20-rbac/pages/UserGroups/views UserGroupsListView.tsx

88.24% Statements 90/102
73.08% Branches 57/78
76% Functions 19/25
88.12% Lines 89/101

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              10x 10x                       10x 10x   10x 10x 10x 10x               10x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x                           10x 44x 44x                                                                     10x 44x 44x     10x 44x 44x 44x   44x 88x     44x         44x 44x 44x   44x   44x                                                                       10x 44x 44x   44x                 1x 1x                         10x 49x 49x 49x 49x 49x 49x     49x                         49x               1x 1x 1x     1x 1x 1x                       49x                         49x 1x 1x 1x     49x           49x           49x           98x                                                 98x     49x         2x                   1x 1x                                                             10x 8x 8x 8x 8x 8x 8x 8x 8x       32x             32x               32x               32x                   8x             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, { useState, useMemo } from 'react'
import {
  Text,
  Layout,
  Button,
  Popover,
  ButtonVariation,
  Icon,
  TableV2,
  useConfirmationDialog,
  useToaster,
  Dialog
} from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import type { CellProps, Renderer, Column } from 'react-table'
import { Classes, Position, Menu, Intent, PopoverInteractionKind, IconName, MenuItem } from '@blueprintjs/core'
import { useHistory, useParams } from 'react-router-dom'
import { noop } from 'lodash-es'
import {
  UserGroupAggregateDTO,
  useDeleteUserGroup,
  ResponsePageUserGroupAggregateDTO,
  UserGroupDTO,
  UserMetadataDTO,
  RoleAssignmentMetadataDTO
} from 'services/cd-ng'
import { useStrings, String } from 'framework/strings'
import RoleBindingsList from '@rbac/components/RoleBindingsList/RoleBindingsList'
import { getUserGroupActionTooltipText, PrincipalType } from '@rbac/utils/utils'
import type { PipelineType, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import routes from '@common/RouteDefinitions'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import ManagePrincipalButton from '@rbac/components/ManagePrincipalButton/ManagePrincipalButton'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import RbacAvatarGroup from '@rbac/components/RbacAvatarGroup/RbacAvatarGroup'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import CopyGroupForm from '../CopyGroupMenuItem/CopyGroupForm'
import css from './UserGroupsListView.module.scss'
 
interface UserGroupsListViewProps {
  data: ResponsePageUserGroupAggregateDTO | null
  gotoPage: (index: number) => void
  reload: () => Promise<void>
  openRoleAssignmentModal: (
    type?: PrincipalType,
    principalInfo?: UserGroupDTO | UserMetadataDTO,
    roleBindings?: RoleAssignmentMetadataDTO[]
  ) => void
  openUserGroupModal: (userGroup?: UserGroupDTO, _isAddMember?: boolean) => void
}
 
export const UserGroupColumn = (data: UserGroupDTO): React.ReactElement => {
  const { getString } = useStrings()
  return (
    <Layout.Vertical>
      <Layout.Vertical spacing="xsmall" padding={{ left: 'small' }}>
        <Layout.Horizontal spacing="medium">
          <Text color={Color.BLACK} lineClamp={1}>
            {data.name}
          </Text>
          {data.ssoLinked ? (
            <Popover interactionKind={PopoverInteractionKind.HOVER}>
              <Icon name="link" color={Color.BLUE_500} size={10} />
              <Layout.Vertical spacing="xsmall" padding="medium">
                <Layout.Horizontal spacing="xsmall">
                  <Text color={Color.BLACK}>
                    <String stringID="rbac.userDetails.linkToSSOProviderModal.saml" />
                  </Text>
                  <Text lineClamp={1}>{data.linkedSsoDisplayName}</Text>
                </Layout.Horizontal>
                <Layout.Horizontal spacing="xsmall">
                  <Text color={Color.BLACK}>
                    <String stringID="rbac.userDetails.linkToSSOProviderModal.group" />
                  </Text>
                  <Text lineClamp={1}>{data.ssoGroupName}</Text>
                </Layout.Horizontal>
              </Layout.Vertical>
            </Popover>
          ) : null}
        </Layout.Horizontal>
        <Text color={Color.GREY_600} lineClamp={1} font={{ variation: FontVariation.SMALL }}>
          {getString('idLabel', { id: data.identifier })}
        </Text>
      </Layout.Vertical>
    </Layout.Vertical>
  )
}
 
const RenderColumnUserGroup: Renderer<CellProps<UserGroupAggregateDTO>> = ({ row }) => {
  const data = row.original.userGroupDTO
  return UserGroupColumn(data)
}
 
const RenderColumnMembers: Renderer<CellProps<UserGroupAggregateDTO>> = ({ row, column }) => {
  const data = row.original
  const { accountIdentifier, orgIdentifier, projectIdentifier, identifier } = data.userGroupDTO
  const { getString } = useStrings()
  const avatars =
    data.users?.map(user => {
      return { email: user.email, name: user.name }
    }) || []
 
  const handleAddMember = (e: React.MouseEvent<HTMLElement | Element, MouseEvent>): void => {
    e.stopPropagation()
    ;(column as any).openUserGroupModal(data.userGroupDTO, true)
  }
 
  const disabled = data.userGroupDTO.ssoLinked || data.userGroupDTO.externallyManaged
  const disableTooltipTextId = data.userGroupDTO ? getUserGroupActionTooltipText(data.userGroupDTO) : undefined
  const disableTooltipText = disableTooltipTextId ? getString(disableTooltipTextId) : undefined
 
  const avatarTooltip = disableTooltipText ? <Text padding="medium">{disableTooltipText}</Text> : undefined
 
  return avatars.length ? (
    <RbacAvatarGroup
      avatars={avatars}
      restrictLengthTo={6}
      onAdd={handleAddMember}
      permission={{
        resourceScope: {
          accountIdentifier,
          orgIdentifier,
          projectIdentifier
        },
        resource: {
          resourceType: ResourceType.USERGROUP,
          resourceIdentifier: identifier
        },
        permission: PermissionIdentifier.MANAGE_USERGROUP
      }}
      disabled={disabled}
      onAddTooltip={avatarTooltip}
    />
  ) : (
    <Layout.Horizontal>
      <ManagePrincipalButton
        text={getString('plusNumber', { number: getString('members') })}
        variation={ButtonVariation.LINK}
        onClick={handleAddMember}
        className={css.roleButton}
        resourceType={ResourceType.USERGROUP}
        resourceIdentifier={identifier}
        disabled={disabled}
        tooltip={disableTooltipText}
      />
    </Layout.Horizontal>
  )
}
 
const RenderColumnRoleAssignments: Renderer<CellProps<UserGroupAggregateDTO>> = ({ row, column }) => {
  const data = row.original.roleAssignmentsMetadataDTO
  const { getString } = useStrings()
 
  return (
    <Layout.Horizontal spacing="small" flex={{ alignItems: 'center', justifyContent: 'flex-start' }}>
      <RoleBindingsList data={data} length={2} />
      <ManagePrincipalButton
        text={getString('common.plusNumber', { number: getString('common.role') })}
        variation={ButtonVariation.LINK}
        data-testid={`addRole-${row.original.userGroupDTO.identifier}`}
        className={css.roleButton}
        onClick={event => {
          event.stopPropagation()
          ;(column as any).openRoleAssignmentModal(
            PrincipalType.USER_GROUP,
            row.original.userGroupDTO,
            row.original.roleAssignmentsMetadataDTO
          )
        }}
        resourceType={ResourceType.USERGROUP}
        resourceIdentifier={row.original.userGroupDTO.identifier}
      />
    </Layout.Horizontal>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<UserGroupAggregateDTO>> = ({ row, column }) => {
  const data = row.original.userGroupDTO
  const { accountIdentifier, orgIdentifier, projectIdentifier, identifier } = data
  const [menuOpen, setMenuOpen] = useState(false)
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const { mutate: deleteUserGroup } = useDeleteUserGroup({
    queryParams: { accountIdentifier, orgIdentifier, projectIdentifier }
  })
  const permissionRequest = {
    resourceScope: {
      accountIdentifier,
      orgIdentifier,
      projectIdentifier
    },
    resource: {
      resourceType: ResourceType.USERGROUP,
      resourceIdentifier: identifier
    },
    permission: PermissionIdentifier.MANAGE_USERGROUP
  }
 
  const { openDialog: openDeleteDialog } = useConfirmationDialog({
    contentText: getString('rbac.userGroupPage.confirmDelete', { name: data.name }),
    titleText: getString('rbac.userGroupPage.confirmDeleteTitle'),
    confirmButtonText: getString('delete'),
    cancelButtonText: getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async (isConfirmed: boolean) => {
      /* istanbul ignore else */ if (isConfirmed) {
        try {
          const deleted = await deleteUserGroup(identifier, {
            headers: { 'content-type': 'application/json' }
          })
          /* istanbul ignore else */ if (deleted) {
            showSuccess(getString('rbac.userGroupPage.successMessage', { name: data.name }))
            ;(column as any).reload()
          } else {
            showError(getString('deleteError'))
          }
        } catch (err) {
          /* istanbul ignore next */
          showError(err?.data?.message || err?.message)
        }
      }
    }
  })
 
  const [openCopyGroupModal, closeCopyGroupModal] = useModalHook(() => {
    return (
      <Dialog
        isOpen={true}
        enforceFocus={false}
        title={getString('rbac.copyGroup.title', { name: data.name })}
        onClose={closeCopyGroupModal}
      >
        <CopyGroupForm closeModal={closeCopyGroupModal} identifier={identifier} />
      </Dialog>
    )
  }, [])
 
  const handleDelete = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    openDeleteDialog()
  }
 
  const handleEdit = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    ;(column as any).openUserGroupModal(data)
  }
 
  const handleCopyUserGroup = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    setMenuOpen(false)
    openCopyGroupModal()
  }
 
  const renderMenuItem = (
    icon: IconName,
    text: string,
    clickHandler: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void,
    tooltipText: string
  ): React.ReactElement => {
    Iif (data.externallyManaged) {
      return (
        <Popover
          position={Position.TOP}
          fill
          usePortal
          inheritDarkTheme={false}
          interactionKind={PopoverInteractionKind.HOVER}
          hoverCloseDelay={50}
          content={
            <div className={css.popover}>
              <Text font={{ variation: FontVariation.SMALL }}>{tooltipText}</Text>
            </div>
          }
        >
          <div
            onClick={(event: React.MouseEvent<HTMLElement, MouseEvent>) => {
              event.stopPropagation()
            }}
          >
            <MenuItem icon={icon} text={text} onClick={clickHandler} disabled />
          </div>
        </Popover>
      )
    }
    return <RbacMenuItem icon={icon} text={text} onClick={clickHandler} permission={permissionRequest} />
  }
 
  return (
    <Layout.Horizontal flex={{ justifyContent: 'flex-end' }}>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          minimal
          icon="Options"
          data-testid={`menu-${data.identifier}`}
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu>
          {renderMenuItem(
            'edit',
            getString('edit'),
            handleEdit,
            getString('rbac.manageSCIMText', {
              action: getString('edit').toLowerCase(),
              target: getString('rbac.group').toLowerCase()
            })
          )}
          {renderMenuItem(
            'trash',
            getString('delete'),
            handleDelete,
            getString('rbac.manageSCIMText', {
              action: getString('delete').toLowerCase(),
              target: getString('rbac.group').toLowerCase()
            })
          )}
          {data.externallyManaged ? (
            <MenuItem icon="duplicate" text={getString('common.copy')} onClick={handleCopyUserGroup} />
          ) : undefined}
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const UserGroupsListView: React.FC<UserGroupsListViewProps> = props => {
  const { data, gotoPage, reload, openRoleAssignmentModal, openUserGroupModal } = props
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<PipelineType<ProjectPathProps>>()
  const { getString } = useStrings()
  const { licenseInformation } = useLicenseStore()
  const isCommunity = isCDCommunity(licenseInformation)
  const history = useHistory()
  const columns: Column<UserGroupAggregateDTO>[] = useMemo(
    () => [
      {
        Header: getString('common.userGroup'),
        id: 'userGroup',
        accessor: row => row.userGroupDTO.name,
        width: '30%',
        Cell: RenderColumnUserGroup
      },
      {
        Header: getString('members'),
        id: 'members',
        accessor: row => row.users,
        width: '30%',
        openUserGroupModal: openUserGroupModal,
        Cell: RenderColumnMembers
      },
      {
        Header: isCommunity ? '' : getString('rbac.roleBinding'),
        id: 'roleBindings',
        accessor: row => row.roleAssignmentsMetadataDTO,
        width: '35%',
        Cell: isCommunity ? () => noop : RenderColumnRoleAssignments,
        openRoleAssignmentModal: openRoleAssignmentModal
      },
      {
        Header: '',
        id: 'menu',
        accessor: row => row.userGroupDTO.identifier,
        width: '5%',
        Cell: RenderColumnMenu,
        reload: reload,
        openUserGroupModal: openUserGroupModal,
        disableSortBy: true
      }
    ],
    [openRoleAssignmentModal, openUserGroupModal, reload]
  )
  return (
    <TableV2<UserGroupAggregateDTO>
      className={css.table}
      columns={columns}
      name="UserGroupsListView"
      data={data?.data?.content || []}
      onRowClick={userGroup => {
        history.push(
          routes.toUserGroupDetails({
            accountId,
            orgIdentifier,
            projectIdentifier,
            module,
            userGroupIdentifier: userGroup.userGroupDTO.identifier
          })
        )
      }}
      pagination={{
        itemCount: data?.data?.totalItems || 0,
        pageSize: data?.data?.pageSize || 10,
        pageCount: data?.data?.totalPages || 0,
        pageIndex: data?.data?.pageIndex || 0,
        gotoPage: gotoPage
      }}
    />
  )
}
 
export default UserGroupsListView