All files / modules/75-ce/components/COK8sClusterSelector COK8sClusterSelector.tsx

84.38% Statements 54/64
64.23% Branches 88/137
57.89% Functions 11/19
83.87% Lines 52/62

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              5x   5x 5x 5x 5x                   5x 5x 5x 5x     5x     5x 5x 5x                     5x   5x 1x 1x 1x                                 5x 1x                       5x                         5x 1x         5x 1x   1x             5x 1x 1x             5x 1x 1x             5x 1x   1x         1x                                                                                                                                             1x   1x                                                                                           5x 2x 2x 2x   2x           2x         2x 1x                 2x       2x 2x                                                                                                                                                                 1x             1x                                                                     5x  
/*
 * 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 } from 'react'
import type { CellProps, Renderer } from 'react-table'
import { isEmpty as _isEmpty } from 'lodash-es'
import classNames from 'classnames'
import ReactTimeago from 'react-timeago'
import {
  Button,
  Container,
  ExpandingSearchInput,
  Icon,
  //   Intent,
  Layout,
  Radio,
  Text
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { Table, TagsPopover } from '@common/components'
import useCreateConnectorModal from '@connectors/modals/ConnectorModal/useCreateConnectorModal'
import { Connectors } from '@connectors/constants'
// import { ConnectorConnectivityDetails, ConnectorResponse, useGetTestConnectionResult } from 'services/cd-ng'
import type { ConnectorInfoDTO, ConnectorResponse } from 'services/cd-ng'
import { StringKeys, useStrings, String } from 'framework/strings'
// import { useParams } from 'react-router-dom'
// import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { ConnectorStatus } from '@ce/constants'
import { DelegateTypes } from '@connectors/pages/connectors/utils/ConnectorUtils'
import css from './COK8sClusterSelector.module.scss'
 
interface COK8sClusterSelectorProps {
  loading: boolean
  search: (t: string) => void
  clusters: ConnectorResponse[]
  selectedCluster: any
  onClusterAddSuccess: (connector: ConnectorResponse) => void
  refetchConnectors: () => Promise<void>
}
 
const TOTAL_ITEMS_PER_PAGE = 8
 
const RenderColumnConnector: Renderer<CellProps<ConnectorResponse>> = ({ row }) => {
  const data = row.original
  const tags = data.connector?.tags || {}
  return (
    <Layout.Horizontal spacing="small">
      <div className={css.wrapper}>
        <Layout.Horizontal spacing="small">
          <div className={css.name} color={Color.BLACK} title={data.connector?.name}>
            {data.connector?.name}
          </div>
          {tags && Object.keys(tags).length ? <TagsPopover tags={tags} /> : null}
        </Layout.Horizontal>
        <div className={css.identifier} title={data.connector?.identifier}>
          {data.connector?.identifier}
        </div>
      </div>
    </Layout.Horizontal>
  )
}
 
const getConnectorDisplaySummaryLabel = (titleStringId: StringKeys, Element: JSX.Element): JSX.Element | string => {
  return (
    <div className={classNames(css.name, css.flex)}>
      {titleStringId ? (
        <Text inline color={Color.BLACK}>
          <String stringID={titleStringId} />:
        </Text>
      ) : null}
      {Element}
    </div>
  )
}
 
const displayDelegatesTagsSummary = (delegateSelectors: []): JSX.Element => {
  return (
    <div className={classNames(css.name)}>
      <Text inline color={Color.BLACK}>
        <String stringID={'delegate.delegateTags'} />:
      </Text>
      <Text inline margin={{ left: 'xsmall' }} color={Color.GREY_400}>
        {delegateSelectors?.join?.(', ')}
      </Text>
    </div>
  )
}
 
const getK8DisplaySummary = (connector: ConnectorInfoDTO): JSX.Element | string => {
  return connector?.spec?.credential?.type === DelegateTypes.DELEGATE_IN_CLUSTER
    ? displayDelegatesTagsSummary(connector.spec.delegateSelectors)
    : getConnectorDisplaySummaryLabel('UrlLabel', <Text>{connector?.spec?.credential?.spec?.masterUrl}</Text>)
}
 
const RenderColumnDetails: Renderer<CellProps<ConnectorResponse>> = ({ row }) => {
  const data = row.original
 
  return data.connector ? (
    <div className={css.wrapper}>
      <div color={Color.BLACK}>{getK8DisplaySummary(data.connector)}</div>
    </div>
  ) : null
}
 
export const RenderColumnActivity: Renderer<CellProps<ConnectorResponse>> = ({ row }) => {
  const data = row.original
  return (
    <Layout.Horizontal spacing="small">
      <Icon name="activity" />
      {data.activityDetails?.lastActivityTime ? <ReactTimeago date={data.activityDetails?.lastActivityTime} /> : null}
    </Layout.Horizontal>
  )
}
export const RenderColumnLastUpdated: Renderer<CellProps<ConnectorResponse>> = ({ row }) => {
  const data = row.original
  return (
    <Layout.Horizontal spacing="small">
      {data.lastModifiedAt ? <ReactTimeago date={data.lastModifiedAt} /> : null}
    </Layout.Horizontal>
  )
}
 
const RenderColumnStatus: Renderer<CellProps<ConnectorResponse>> = ({ row }) => {
  const data = row.original
  //   const { accountId } = useParams<AccountPathProps>()
  const [testing, setTesting] = useState(false)
  //   const [lastTestedAt, setLastTestedAt] = useState<number>()
  //   const [status, setStatus] = useState<ConnectorConnectivityDetails['status']>(data.status?.status)
 
  //   const [errorMessage, setErrorMessage] = useState<ErrorMessage>()
  const { getString } = useStrings()
  //   const { branch, repoIdentifier } = data.gitDetails || {}
  //   const [stepDetails, setStepDetails] = useState<StepDetails>({
  //     step: 1,
  //     intent: Intent.WARNING,
  //     status: 'PROCESS' // Replace when enum is added in uikit
  //   })
 
  //   const { mutate: reloadTestConnection } = useGetTestConnectionResult({
  //     identifier: data.connector?.identifier || '',
  //     queryParams: {
  //       accountIdentifier: accountId,
  //       branch,
  //       repoIdentifier
  //     },
  //     requestOptions: {
  //       headers: {
  //         'content-type': 'application/json'
  //       }
  //     }
  //   })
 
  //   const executeStepVerify = async (): Promise<void> => {
  //     if (stepDetails.step === StepIndex.get(STEP.TEST_CONNECTION)) {
  //       if (stepDetails.status === 'PROCESS') {
  //         try {
  //           const result = await reloadTestConnection()
  //           setStatus(result?.data?.status)
  //           setLastTestedAt(new Date().getTime())
  //           if (result?.data?.status === 'SUCCESS') {
  //             setStepDetails({
  //               step: 2,
  //               intent: Intent.SUCCESS,
  //               status: 'DONE'
  //             })
  //           } else {
  //             setErrorMessage({ ...result.data, useErrorHandler: false })
  //             setStepDetails({
  //               step: 1,
  //               intent: Intent.DANGER,
  //               status: 'ERROR'
  //             })
  //           }
  //           setTesting(false)
  //         } catch (err) {
  //           setLastTestedAt(new Date().getTime())
  //           setStatus('FAILURE')
  //           if (err?.data?.responseMessages) {
  //             setErrorMessage({
  //               errorSummary: err?.data?.message,
  //               errors: err?.data?.responseMessages || [],
  //               useErrorHandler: true
  //             })
  //           } else {
  //             setErrorMessage({ ...err.message, useErrorHandler: false })
  //           }
  //           setStepDetails({
  //             step: 1,
  //             intent: Intent.DANGER,
  //             status: 'ERROR'
  //           })
  //           setTesting(false)
  //         }
  //       }
  //     }
  //   }
 
  //   useEffect(() => {
  //     if (testing) executeStepVerify()
  //   }, [testing])
 
  const isStatusSuccess = status === ConnectorStatus.SUCCESS || data.status?.status === ConnectorStatus.SUCCESS
 
  return (
    <Layout.Horizontal>
      {!testing && (
        <Layout.Vertical width="100px">
          <Layout.Horizontal spacing="small">
            {data.status?.status ? (
              <Text
                inline
                icon={isStatusSuccess ? 'full-circle' : 'warning-sign'}
                iconProps={{
                  size: isStatusSuccess ? 6 : 12,
                  color: isStatusSuccess ? Color.GREEN_500 : Color.RED_500
                }}
              >
                {isStatusSuccess ? getString('active').toLowerCase() : getString('error').toLowerCase()}
              </Text>
            ) : null}
          </Layout.Horizontal>
          {/* {status || data.status?.status ? (
            <Text font={{ size: 'small' }} color={Color.GREY_400}>
              <ReactTimeago date={lastTestedAt || data.status?.testedAt || ''} />
            </Text>
          ) : null} */}
        </Layout.Vertical>
      )}
      {!testing && !isStatusSuccess && (
        <Button
          font="small"
          className={css.testBtn}
          text={getString('test').toUpperCase()}
          onClick={e => {
            e.stopPropagation()
            setTesting(true)
            // setStepDetails({
            //   step: 1,
            //   intent: Intent.WARNING,
            //   status: 'PROCESS' // Replace when enum is added in uikit
            // })
          }}
          withoutBoxShadow
        />
      )}
    </Layout.Horizontal>
  )
}
 
const COK8sClusterSelector: React.FC<COK8sClusterSelectorProps> = props => {
  const { getString } = useStrings()
  const [pageIndex, setPageIndex] = useState<number>(0)
  const [selectedCluster, setSelectedCluster] = useState<any>(props.selectedCluster)
 
  const { openConnectorModal } = useCreateConnectorModal({
    onSuccess: () => {
      props.refetchConnectors()
    }
  })
 
  const handleSearch = (text: string) => {
    pageIndex !== 0 && setPageIndex(0)
    props.search(text)
  }
 
  const TableCheck = (tableProps: CellProps<any>) => {
    return (
      <Radio
        className={css.radioSelector}
        checked={selectedCluster?.connector?.name === tableProps.row.original.connector.name}
        onClick={_ => setSelectedCluster(tableProps.row.original)}
      />
    )
  }
 
  const addConnector = () => {
    props.onClusterAddSuccess(selectedCluster)
  }
 
  const hasSelectedCluster = !_isEmpty(selectedCluster)
  return (
    <Container>
      <Layout.Vertical spacing={'large'}>
        <Text font={'large'} className={css.header}>
          Select Connector
        </Text>
        <Layout.Horizontal className={css.infoSection}>
          <Icon name={'info'} size={24} />
          <div>
            <Text>
              The connectors shown below are the clusters who are connected to a <span>Harness Delegate</span>
            </Text>
            <Text>
              A <span>Harness Delegate</span> is a service that can run in local network or VPC to connect artifact
              servers, infrastructure and verification providers to install projects and pipelines. If the cluster you
              would like to monitor does not have a Harness delegate connected to it, you will have to create a
              connector
            </Text>
          </div>
        </Layout.Horizontal>
        <Layout.Horizontal
          style={{
            paddingBottom: 20,
            paddingTop: 20,
            borderBottom: '1px solid #CDD3DD',
            justifyContent: 'space-between'
          }}
        >
          <Layout.Horizontal spacing={'medium'} className={css.ctaContainer}>
            <Button
              onClick={addConnector}
              disabled={!hasSelectedCluster}
              style={{
                backgroundColor: selectedCluster ? '#0278D5' : 'inherit',
                color: selectedCluster ? '#F3F3FA' : 'inherit'
              }}
              withoutBoxShadow
            >
              {'Add selected'}
            </Button>
            <Button
              withoutBoxShadow
              className={css.borderBtn}
              onClick={() =>
                openConnectorModal(false, Connectors.CE_KUBERNETES, {
                  connectorInfo: {
                    orgIdentifier: '',
                    projectIdentifier: '',
                    spec: { featuresEnabled: ['VISIBILITY', 'OPTIMIZATION'] }
                  } as unknown as ConnectorInfoDTO
                })
              }
            >
              {'+ Create a new connector'}
            </Button>
          </Layout.Horizontal>
          <ExpandingSearchInput onChange={handleSearch} />
        </Layout.Horizontal>
        <Container>
          {props.loading && (
            <Layout.Horizontal flex={{ justifyContent: 'center' }}>
              <Icon name="spinner" size={24} color="blue500" />
            </Layout.Horizontal>
          )}
          {!props.loading && (
            <Table<ConnectorResponse>
              data={(props.clusters || []).slice(
                pageIndex * TOTAL_ITEMS_PER_PAGE,
                pageIndex * TOTAL_ITEMS_PER_PAGE + TOTAL_ITEMS_PER_PAGE
              )}
              pagination={{
                pageSize: TOTAL_ITEMS_PER_PAGE,
                pageIndex: pageIndex,
                pageCount: Math.ceil((props.clusters || []).length / TOTAL_ITEMS_PER_PAGE),
                itemCount: (props.clusters || []).length,
                gotoPage: newPageIndex => setPageIndex(newPageIndex)
              }}
              columns={[
                { Header: '', id: 'selected', Cell: TableCheck, width: '5%' },
                {
                  Header: getString('connector').toUpperCase(),
                  accessor: row => row.connector?.name,
                  id: 'name',
                  width: '20%',
                  Cell: RenderColumnConnector
                },
                {
                  Header: getString('details').toUpperCase(),
                  accessor: row => row.connector?.description,
                  id: 'details',
                  width: '20%',
                  Cell: RenderColumnDetails
                },
                {
                  Header: getString('lastActivity').toUpperCase(),
                  accessor: 'activityDetails',
                  id: 'activity',
                  width: '20%',
                  Cell: RenderColumnActivity
                },
                {
                  Header: getString('connectivityStatus').toUpperCase(),
                  accessor: 'status',
                  id: 'status',
                  width: '15%',
                  Cell: RenderColumnStatus
                },
                {
                  Header: getString('lastUpdated').toUpperCase(),
                  accessor: 'lastModifiedAt',
                  id: 'lastModifiedAt',
                  width: '20%',
                  Cell: RenderColumnLastUpdated
                }
              ]}
            />
          )}
        </Container>
      </Layout.Vertical>
    </Container>
  )
}
 
export default COK8sClusterSelector