All files / modules/30-delegates/components/DelegateTokens DelegateTokens.tsx

88.16% Statements 67/76
51.56% Branches 33/64
73.91% Functions 17/23
87.67% Lines 64/73

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              9x 9x 9x   9x 9x 9x                             9x   9x   9x   9x 9x   9x 9x 9x   9x           9x   9x 13x 12x 12x 12x   12x             12x                 12x 12x 12x 12x     12x 8x         8x 8x   8x         12x 12x   12x   12x 24x         12x 24x       24x         12x 24x       12x 24x         2x 2x               12x 24x 24x                                                           12x 12x 12x                 12x 6x                                                             12x                                     12x 6x 6x           12x   12x               2x 2x                                                                                                         1x                         9x  
/*
 * Copyright 2022 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, { useEffect, useState, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import ReactTimeago from 'react-timeago'
import type { CellProps, Renderer, Column } from 'react-table'
import { Menu, MenuItem, Classes, Position } from '@blueprintjs/core'
import { get } from 'lodash-es'
import {
  Container,
  Layout,
  ExpandingSearchInput,
  PageError,
  shouldShowError,
  Checkbox,
  TableV2,
  Button,
  Popover,
  ButtonVariation,
  Icon,
  NoDataCard
} from '@wings-software/uicore'
 
import { PageSpinner } from '@common/components'
 
import { useGetDelegateTokens, GetDelegateTokensQueryParams } from 'services/cd-ng'
 
import { useStrings } from 'framework/strings'
import type { DelegateTokenDetails } from 'services/portal'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, DelegateActions } from '@common/constants/TrackingConstants'
 
import { useRevokeTokenModal } from './modals/useRevokeTokenModal'
import { useCreateTokenModal } from './modals/useCreateTokenModal'
import { useMoreTokenInfoModalModal } from './modals/useMoreTokenInfoModal'
 
import css from './DelegateTokens.module.scss'
 
type CustomColumn<T extends Record<string, any>> = Column<T> & {
  reload?: () => void
}
 
const delegatesPerPage = 10
 
export const DelegateListing: React.FC = () => {
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<Record<string, string>>()
  const [showRevoked, setShowRevoked] = useState<boolean>(false)
  const [searchString, setSearchString] = useState<string>('')
 
  const [page, setPage] = useState(0)
 
  const {
    data: tokensResponse,
    refetch: getDelegateTokens,
    error: tokenFetchError,
    loading: showLoader
  } = useGetDelegateTokens({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      status: 'ACTIVE'
    } as GetDelegateTokensQueryParams
  })
 
  const pageTokens = useMemo(() => {
    const tokens = get(tokensResponse, 'resource', [])
    const searchedTokens = tokens.filter(token => token?.name?.toLowerCase().includes(searchString.toLowerCase()))
    return searchedTokens.splice(page * delegatesPerPage, (page + 1) * delegatesPerPage)
  }, [tokensResponse, page, searchString])
 
  const getTokens = () => {
    const queryParams = {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier
    } as GetDelegateTokensQueryParams
    Eif (!showRevoked) {
      queryParams.status = 'ACTIVE'
    }
    getDelegateTokens({
      queryParams
    })
  }
 
  const { openRevokeTokenModal } = useRevokeTokenModal({ onSuccess: getTokens })
  const { openMoreTokenInfoModal } = useMoreTokenInfoModalModal({})
 
  const { openCreateTokenModal } = useCreateTokenModal({ onSuccess: getTokens })
 
  const RenderColumnName: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => (
    <span className={`${css.tokenNameColumn} ${css.tokenCellText}`}>
      <Icon name="key" size={28} margin={{ right: 'small' }} />
      {row.original.name}
    </span>
  )
  const RenderColumnCreatedAt: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => (
    <span className={css.tokenCellText}>
      {row.original.createdAt && <ReactTimeago date={row.original.createdAt} />}
    </span>
  )
  const RenderColumnCreatedBy: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => (
    <span className={css.tokenCellText}>
      {row.original?.createdByNgUser?.username?.toLowerCase?.() || getString('na')}
    </span>
  )
  const RenderColumnStatus: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => (
    <span className={css.tokenCellText}>
      {row.original.status === 'ACTIVE' ? getString('active') : getString('delegates.tokens.revoked')}
    </span>
  )
  const RenderColumnActions: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => (
    <span className={css.tokenCellText}>
      {row.original.status !== 'REVOKED' && (
        <Button
          variation={ButtonVariation.SECONDARY}
          onClick={e => {
            e.stopPropagation()
            openRevokeTokenModal(row.original.name || '')
          }}
        >
          {getString('delegates.tokens.revoke')}
        </Button>
      )}
    </span>
  )
  const RenderColumnMenu: Renderer<CellProps<DelegateTokenDetails>> = ({ row }) => {
    const [menuOpen, setMenuOpen] = useState(false)
    return (
      <Layout.Horizontal className={css.menuColumn}>
        <Popover
          isOpen={menuOpen}
          onInteraction={nextOpenState => {
            setMenuOpen(nextOpenState)
          }}
          className={Classes.DARK}
          position={Position.RIGHT_TOP}
        >
          <Button
            minimal
            icon="Options"
            onClick={e => {
              e.stopPropagation()
              setMenuOpen(true)
            }}
          />
          <Menu style={{ minWidth: 'unset' }}>
            <MenuItem
              icon="edit"
              text={getString('delegates.tokens.moreInfo')}
              onClick={() => openMoreTokenInfoModal(row.original.name || '')}
            />
          </Menu>
        </Popover>
      </Layout.Horizontal>
    )
  }
 
  const pagination = useMemo(() => {
    const itemCount = get(tokensResponse, 'resource', []).length
    return {
      itemCount,
      pageSize: delegatesPerPage,
      pageCount: Math.ceil(itemCount / delegatesPerPage),
      pageIndex: page,
      gotoPage: setPage
    }
  }, [page, setPage, pageTokens])
 
  const columns: CustomColumn<DelegateTokenDetails>[] = useMemo(
    () => [
      {
        Header: getString('name').toUpperCase(),
        accessor: 'name',
        id: 'name',
        width: '33%',
        Cell: RenderColumnName
      },
      {
        Header: getString('createdAt').toUpperCase(),
        accessor: 'createdAt',
        id: 'createdAt',
        width: '20%',
        Cell: RenderColumnCreatedAt
      },
      {
        Header: getString('createdBy').toUpperCase(),
        accessor: 'createdBy',
        id: 'createdBy',
        width: '20%',
        Cell: RenderColumnCreatedBy
      },
      {
        Header: getString('status').toUpperCase(),
        accessor: 'status',
        id: 'activity',
        width: '15%',
        Cell: RenderColumnStatus
      },
      {
        Header: '',
        accessor: row => row.value,
        width: '10%',
        id: 'actions',
        Cell: RenderColumnActions,
        reload: getTokens,
        disableSortBy: true
      },
      {
        Header: '',
        width: '3%',
        id: 'menu',
        Cell: RenderColumnMenu,
        reload: getTokens,
        disableSortBy: true
      }
    ],
    []
  )
 
  useEffect(() => {
    Eif (page === 0) {
      getTokens()
    } else {
      setPage(0)
    }
  }, [showRevoked])
 
  const { trackEvent } = useTelemetry()
 
  return (
    <Container height="100%">
      <Layout.Horizontal className={css.header}>
        <Button
          intent="primary"
          text={getString('rbac.token.createLabel')}
          icon="plus"
          onClick={() => {
            openCreateTokenModal()
            trackEvent(DelegateActions.LoadCreateTokenModal, {
              category: Category.DELEGATE
            })
          }}
          id="newDelegateBtn"
          data-testid="newDelegateButton"
        />
        <Layout.Horizontal>
          <Checkbox
            onChange={() => {
              setShowRevoked(!showRevoked)
            }}
            checked={showRevoked}
            large
            label={getString('delegates.tokens.showRevoked')}
            className={css.revokeCheckbox}
          />
          <ExpandingSearchInput
            alwaysExpanded
            width={250}
            placeholder={getString('search')}
            throttle={200}
            onChange={text => {
              setSearchString(text)
              setPage(0)
            }}
            className={css.search}
          />
        </Layout.Horizontal>
      </Layout.Horizontal>
 
      <Layout.Vertical className={css.listBody}>
        {showLoader ? (
          <div style={{ position: 'relative', height: 'calc(100vh - 128px)' }}>
            <PageSpinner />
          </div>
        ) : tokenFetchError && shouldShowError(tokenFetchError) ? (
          <PageError
            message={(tokenFetchError?.data as Error)?.message || tokenFetchError?.message}
            onClick={() => {
              getTokens()
            }}
          />
        ) : (
          <Container className={css.delegateListContainer}>
            {pageTokens.length ? (
              <TableV2<DelegateTokenDetails>
                sortable={true}
                className={css.table}
                columns={columns}
                data={pageTokens}
                name="TokensListView"
                onRowClick={({ name }) => {
                  openMoreTokenInfoModal(name || '')
                }}
                pagination={pagination}
              />
            ) : (
              <NoDataCard icon="resources-icon" message={getString('delegates.tokens.noTokens')}></NoDataCard>
            )}
          </Container>
        )}
      </Layout.Vertical>
    </Container>
  )
}
export default DelegateListing