All files / modules/20-rbac/pages/ServiceAccounts/views ServiceAccountsListView.tsx

94.87% Statements 74/78
70.45% Branches 31/44
90.48% Functions 19/21
94.87% Lines 74/78

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              10x 10x 10x                   10x   10x 10x 10x             10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x                           10x 48x 48x 48x                                   10x 48x 48x   48x                 1x 1x                                   10x 48x 48x             10x 48x 48x             10x 53x 53x 53x 53x 53x 53x       53x               1x 1x 1x     1x 1x 1x                       53x 1x 1x 1x     53x           53x         2x                   1x 1x                                                                   10x             8x 8x 8x 8x 8x 8x 5x     30x               30x               30x             30x             30x                     8x             1x                   48x                       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 { useHistory, useParams } from 'react-router-dom'
import {
  Avatar,
  Button,
  ButtonVariation,
  Layout,
  Popover,
  TableV2,
  Text,
  useConfirmationDialog
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import type { CellProps, Column, Renderer } from 'react-table'
import { Classes, Intent, Menu, Position } from '@blueprintjs/core'
import { noop } from 'lodash-es'
import {
  PageServiceAccountAggregateDTO,
  RoleAssignmentMetadataDTO,
  ServiceAccountAggregateDTO,
  ServiceAccountDTO,
  useDeleteServiceAccount
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { TagsPopover, useToaster } from '@common/components'
import RoleBindingsList from '@rbac/components/RoleBindingsList/RoleBindingsList'
import routes from '@common/RouteDefinitions'
import type { PipelineType, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import { PrincipalType } from '@rbac/utils/utils'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import css from './ServiceAccountsListView.module.scss'
 
interface ServiceAccountsListViewProps {
  data?: PageServiceAccountAggregateDTO
  reload: () => void
  openRoleAssignmentModal: (
    type?: PrincipalType,
    principalInfo?: ServiceAccountDTO,
    roleBindings?: RoleAssignmentMetadataDTO[]
  ) => void
  openServiceAccountModal: (serviceAccount?: ServiceAccountDTO) => void
  gotoPage: (index: number) => void
}
 
const RenderColumnDetails: Renderer<CellProps<ServiceAccountAggregateDTO>> = ({ row }) => {
  const data = row.original.serviceAccount
  const { getString } = useStrings()
  return (
    <Layout.Horizontal spacing="small" padding={{ right: 'small' }}>
      <Avatar name={data.name} hoverCard={false} />
      <div>
        <Layout.Horizontal spacing="small">
          <Text color={Color.BLACK} lineClamp={1} className={css.wordBreak}>
            {data.name}
          </Text>
          {data.tags && Object.keys(data.tags).length ? <TagsPopover tags={data.tags} /> : null}
        </Layout.Horizontal>
        <Text color={Color.GREY_400} lineClamp={1} font={{ size: 'small' }} className={css.wordBreak}>
          {getString('idLabel', { id: data.identifier })}
        </Text>
      </div>
    </Layout.Horizontal>
  )
}
 
const RenderColumnRoleAssignments: Renderer<CellProps<ServiceAccountAggregateDTO>> = ({ row, column }) => {
  const data = row.original
  const { getString } = useStrings()
 
  return (
    <Layout.Horizontal spacing="small" flex={{ alignItems: 'center', justifyContent: 'flex-start' }}>
      <RoleBindingsList data={data.roleAssignmentsMetadataDTO} length={2} />
      <RbacButton
        text={getString('common.plusNumber', { number: getString('common.role') })}
        variation={ButtonVariation.LINK}
        className={css.roleButton}
        data-testid={`addRole-${data.serviceAccount.identifier}`}
        onClick={event => {
          event.stopPropagation()
          ;(column as any).openRoleAssignmentModal(
            PrincipalType.SERVICE,
            data.serviceAccount,
            data.roleAssignmentsMetadataDTO
          )
        }}
        permission={{
          permission: PermissionIdentifier.EDIT_SERVICEACCOUNT,
          resource: {
            resourceType: ResourceType.SERVICEACCOUNT,
            resourceIdentifier: data.serviceAccount.identifier
          }
        }}
      />
    </Layout.Horizontal>
  )
}
 
const RenderColumnApiKeyCount: Renderer<CellProps<ServiceAccountAggregateDTO>> = ({ row }) => {
  const data = row.original
  return (
    <Text padding={{ right: 'small' }} lineClamp={1}>
      {data.tokensCount}
    </Text>
  )
}
 
const RenderColumnEmail: Renderer<CellProps<ServiceAccountAggregateDTO>> = ({ row }) => {
  const data = row.original.serviceAccount
  return (
    <Text padding={{ right: 'small' }} lineClamp={1} className={css.wordBreak}>
      {data.email}
    </Text>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<ServiceAccountAggregateDTO>> = ({ row, column }) => {
  const data = row.original.serviceAccount
  const { accountIdentifier, orgIdentifier, projectIdentifier, identifier } = data
  const [menuOpen, setMenuOpen] = useState(false)
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const { mutate: deleteServiceAccount } = useDeleteServiceAccount({
    queryParams: { accountIdentifier: accountIdentifier || '', orgIdentifier, projectIdentifier }
  })
 
  const { openDialog: openDeleteDialog } = useConfirmationDialog({
    contentText: getString('rbac.serviceAccounts.confirmDelete', { name: data.name }),
    titleText: getString('rbac.serviceAccounts.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 deleteServiceAccount(identifier || '', {
            headers: { 'content-type': 'application/json' }
          })
          /* istanbul ignore else */ if (deleted) {
            showSuccess(getString('rbac.serviceAccounts.successMessage', { name: data.name }))
            ;(column as any).reload()
          } else {
            showError(getString('deleteError'))
          }
        } catch (err) {
          /* istanbul ignore next */
          showError(err?.data?.message || err?.message)
        }
      }
    }
  })
 
  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).openServiceAccountModal(data)
  }
 
  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>
          <RbacMenuItem
            icon="edit"
            text={getString('edit')}
            onClick={handleEdit}
            permission={{
              permission: PermissionIdentifier.EDIT_SERVICEACCOUNT,
              resource: {
                resourceType: ResourceType.SERVICEACCOUNT,
                resourceIdentifier: data.identifier
              }
            }}
          />
          <RbacMenuItem
            icon="trash"
            text={getString('delete')}
            onClick={handleDelete}
            permission={{
              permission: PermissionIdentifier.DELETE_SERVICEACCOUNT,
              resource: {
                resourceType: ResourceType.SERVICEACCOUNT,
                resourceIdentifier: data.identifier
              }
            }}
          />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const ServiceAccountsListView: React.FC<ServiceAccountsListViewProps> = ({
  data,
  reload,
  openRoleAssignmentModal,
  openServiceAccountModal,
  gotoPage
}) => {
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<PipelineType<ProjectPathProps>>()
  const { getString } = useStrings()
  const { licenseInformation } = useLicenseStore()
  const isCommunity = isCDCommunity(licenseInformation)
  const history = useHistory()
  const columns: Column<ServiceAccountAggregateDTO>[] = useMemo(
    () => [
      {
        Header: getString('serviceAccount'),
        accessor: row => row.serviceAccount.name,
        id: 'name',
        width: '30%',
        Cell: RenderColumnDetails
      },
      {
        Header: isCommunity ? '' : getString('rbac.roleBinding'),
        id: 'roleBindings',
        accessor: row => row.roleAssignmentsMetadataDTO,
        width: '35%',
        Cell: isCommunity ? () => noop : RenderColumnRoleAssignments,
        openRoleAssignmentModal: openRoleAssignmentModal
      },
      {
        Header: getString('common.apiKeys'),
        id: 'apiKeys',
        accessor: row => row.tokensCount,
        width: '10%',
        Cell: RenderColumnApiKeyCount
      },
      {
        Header: getString('email'),
        id: 'email',
        accessor: row => row.serviceAccount.email,
        width: '20%',
        Cell: RenderColumnEmail
      },
      {
        Header: '',
        id: 'menu',
        accessor: row => row.serviceAccount.identifier,
        width: '5%',
        Cell: RenderColumnMenu,
        reload: reload,
        openServiceAccountModal: openServiceAccountModal,
        disableSortBy: true
      }
    ],
    []
  )
 
  return (
    <TableV2
      data={data?.content || []}
      columns={columns}
      className={css.table}
      name="ServiceAccountsListView"
      onRowClick={serviceAcc => {
        history.push(
          routes.toServiceAccountDetails({
            accountId,
            orgIdentifier,
            projectIdentifier,
            module,
            serviceAccountIdentifier: serviceAcc.serviceAccount.identifier
          })
        )
      }}
      rowDataTestID={serviceAcc => `row-${serviceAcc.serviceAccount.identifier}`}
      pagination={{
        itemCount: data?.totalItems || 0,
        pageSize: data?.pageSize || 10,
        pageCount: data?.totalPages || 0,
        pageIndex: data?.pageIndex || 0,
        gotoPage: gotoPage
      }}
    />
  )
}
 
export default ServiceAccountsListView