All files / modules/20-rbac/pages/Users/views PendingUsersListView.tsx

83.87% Statements 78/93
57.33% Branches 86/150
76.92% Functions 20/26
84.78% Lines 78/92

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              11x 11x                         11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x             11x 4x 4x                       11x 4x   4x                     11x 4x   4x           11x 4x   4x                     11x 9x 9x 9x 9x 9x 9x 9x 9x   9x               1x 1x 1x 1x 1x               9x                           9x 1x 1x 1x     9x         2x                   1x 1x                                                                   11x 2x 2x 2x 2x 2x   2x                         2x 2x     2x 2x     2x       2x 2x     2x 2x       4x             4x               4x             4x             4x                   2x               4x                                                                                   11x  
/*
 * 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, useEffect } from 'react'
import {
  Text,
  Layout,
  Button,
  Popover,
  Avatar,
  ButtonVariation,
  useConfirmationDialog,
  useToaster,
  Page,
  TableV2
} from '@wings-software/uicore'
import type { CellProps, Renderer, Column } from 'react-table'
import { Classes, Position, Menu, Tag, Intent } from '@blueprintjs/core'
import { useParams } from 'react-router-dom'
import { noop } from 'lodash-es'
import { Invite, useDeleteInvite, useGetPendingUsersAggregated, useUpdateInvite } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import RoleBindingsList from '@rbac/components/RoleBindingsList/RoleBindingsList'
import { useRoleAssignmentModal } from '@rbac/modals/RoleAssignmentModal/useRoleAssignmentModal'
import type { AccountPathProps, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useMutateAsGet } from '@common/hooks'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { setPageNumber } from '@common/utils/utils'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './UserListView.module.scss'
 
interface PendingUserListViewProps {
  searchTerm?: string
  shouldReload?: boolean
}
 
const RenderColumnUser: Renderer<CellProps<Invite>> = ({ row }) => {
  const data = row.original
  return (
    <Layout.Horizontal
      spacing="small"
      className={css.overflow}
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      <Avatar name={data.name || data.email} email={data.email} hoverCard={false} />
      <Text lineClamp={1}>{data.name || data.email.split('@')[0]}</Text>
    </Layout.Horizontal>
  )
}
const RenderColumnRoleAssignments: Renderer<CellProps<Invite>> = ({ row }) => {
  const data = row.original.roleBindings
 
  return (
    <Layout.Horizontal
      spacing="small"
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      <RoleBindingsList data={data} length={2} />
    </Layout.Horizontal>
  )
}
 
const RenderColumnStatus: Renderer<CellProps<Invite>> = () => {
  const { getString } = useStrings()
 
  return (
    <Tag round className={css.invitation}>
      {getString('rbac.usersPage.pendingInvitation')}
    </Tag>
  )
}
const RenderColumnEmail: Renderer<CellProps<Invite>> = ({ row }) => {
  const data = row.original
 
  return (
    <Layout.Horizontal
      className={css.overflow}
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      <Text>{data.email}</Text>
    </Layout.Horizontal>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<Invite>> = ({ row, column }) => {
  const data = row.original
  const { accountId } = useParams<AccountPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const [menuOpen, setMenuOpen] = useState(false)
  const { mutate: updateInvite } = useUpdateInvite({ inviteId: data.id, queryParams: { accountIdentifier: accountId } })
  const { showSuccess, showError } = useToaster()
  const { getString } = useStrings()
  const { mutate: deleteUser } = useDeleteInvite({})
 
  const { openDialog } = useConfirmationDialog({
    contentText: getString('rbac.usersPage.deleteConfirmation', { name: data?.name || data?.email }),
    titleText: getString('rbac.usersPage.deleteTitle'),
    confirmButtonText: getString('delete'),
    cancelButtonText: getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async didConfirm => {
      Eif (didConfirm && data) {
        try {
          const deleted = await deleteUser(data.id, { headers: { 'content-type': 'application/json' } })
          deleted && showSuccess(getString('rbac.usersPage.deleteSuccessMessage', { name: data?.name || data?.email }))
          ;(column as any).refetchPendingUsers?.()
        } catch (err) {
          showError(getRBACErrorMessage(err))
        }
      }
    }
  })
 
  const handleResend = async (e: React.MouseEvent<HTMLElement, MouseEvent>): Promise<void> => {
    e.stopPropagation()
    setMenuOpen(false)
    try {
      const updated = await updateInvite(data, { pathParams: { inviteId: data.id } })
      if (updated) {
        ;(column as any).refetchPendingUsers?.()
        showSuccess(getString('rbac.usersPage.resendInviteSuccess', { name: data.email }))
      }
    } catch (err) {
      showError(getRBACErrorMessage(err))
    }
  }
 
  const handleDelete = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    openDialog()
  }
 
  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.id}`}
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu>
          <RbacMenuItem
            icon="reset"
            text={getString('rbac.usersPage.resendInvite')}
            onClick={handleResend}
            permission={{
              resource: {
                resourceType: ResourceType.USER,
                resourceIdentifier: data.id
              },
              permission: PermissionIdentifier.INVITE_USER
            }}
          />
          <RbacMenuItem
            icon="trash"
            text={getString('delete')}
            onClick={handleDelete}
            permission={{
              resource: {
                resourceType: ResourceType.USER,
                resourceIdentifier: data.id
              },
              permission: PermissionIdentifier.INVITE_USER
            }}
          />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const PendingUserListView: React.FC<PendingUserListViewProps> = ({ searchTerm, shouldReload }) => {
  const { licenseInformation } = useLicenseStore()
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const [page, setPage] = useState(0)
  const isCommunity = isCDCommunity(licenseInformation)
 
  const { data, loading, error, refetch } = useMutateAsGet(useGetPendingUsersAggregated, {
    body: {},
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pageIndex: page,
      pageSize: 10,
      searchTerm: searchTerm
    },
    debounce: 300
  })
 
  useEffect(() => {
    setPageNumber({ setPage, page, pageItemsCount: data?.data?.pageItemCount })
  }, [data?.data])
 
  useEffect(() => {
    Iif (searchTerm) setPage(0)
  }, [searchTerm])
 
  const { openRoleAssignmentModal } = useRoleAssignmentModal({
    onSuccess: refetch
  })
 
  useEffect(() => {
    shouldReload && refetch()
  }, [shouldReload])
 
  const columns: Column<Invite>[] = useMemo(
    () => [
      {
        Header: getString('users'),
        id: 'user',
        accessor: row => row.name,
        width: '25%',
        Cell: RenderColumnUser
      },
      {
        Header: isCommunity ? '' : getString('rbac.usersPage.roleBinding'),
        id: 'roleBinding',
        accessor: row => row.roleBindings,
        width: '35%',
        Cell: isCommunity ? () => noop : RenderColumnRoleAssignments,
        openRoleAssignmentModal: openRoleAssignmentModal
      },
      {
        Header: getString('status'),
        id: 'status',
        accessor: row => row.id,
        width: '15%',
        Cell: RenderColumnStatus
      },
      {
        Header: getString('email'),
        id: 'email',
        accessor: row => row.email,
        width: '20%',
        Cell: RenderColumnEmail
      },
      {
        Header: '',
        id: 'menu',
        accessor: row => row.approved,
        width: '5%',
        Cell: RenderColumnMenu,
        refetchPendingUsers: refetch,
        disableSortBy: true
      }
    ],
    [openRoleAssignmentModal, refetch]
  )
 
  return (
    <Page.Body
      loading={loading}
      error={(error as any)?.data?.message || error?.message}
      retryOnError={() => refetch()}
      noData={
        !searchTerm
          ? {
              when: () => !data?.data?.content?.length,
              icon: 'nav-project',
              message: getString('rbac.usersPage.noDataDescription'),
              button: (
                <RbacButton
                  text={getString('newUser')}
                  variation={ButtonVariation.PRIMARY}
                  icon="plus"
                  onClick={() => openRoleAssignmentModal()}
                  permission={{
                    resource: {
                      resourceType: ResourceType.USER
                    },
                    permission: PermissionIdentifier.INVITE_USER
                  }}
                />
              )
            }
          : {
              when: () => !data?.data?.content?.length,
              icon: 'nav-project',
              message: getString('rbac.usersPage.noUsersFound')
            }
      }
    >
      <TableV2<Invite>
        className={css.table}
        columns={columns}
        name="PendingUsersListView"
        data={data?.data?.content || []}
        pagination={{
          itemCount: data?.data?.totalItems || 0,
          pageSize: data?.data?.pageSize || 10,
          pageCount: data?.data?.totalPages || 0,
          pageIndex: data?.data?.pageIndex || 0,
          gotoPage: (pageNumber: number) => setPage(pageNumber)
        }}
      />
    </Page.Body>
  )
}
 
export default PendingUserListView