All files / modules/35-connectors/pages/connectors/views/connectivityStatus ConnectivityStatus.tsx

82.5% Statements 66/80
56.9% Branches 66/116
80% Functions 8/10
82.5% Lines 66/80

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              12x 12x                   12x 12x 12x 12x   12x 12x 12x               12x   12x   12x 12x   12x                               12x                                                       12x         116x 52x           64x     12x 1x   12x 120x 120x 120x 120x   120x 120x 120x 120x 120x           120x   120x                               120x 1x 1x 1x 1x 1x 1x 1x                         1x                                           120x   120x           52x                         120x 120x 120x   120x 18x                           120x 116x 64x   52x         52x 52x 34x     18x     120x 4x                                   116x                         1x 1x 1x 1x                         12x  
/*
 * 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, { MouseEvent, ReactElement, useState } from 'react'
import {
  Text,
  Layout,
  Button,
  Popover,
  StepsProgress,
  ButtonVariation,
  ButtonSize,
  IconName
} from '@wings-software/uicore'
import { Position, Intent, PopoverInteractionKind } from '@blueprintjs/core'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import ReactTimeago from 'react-timeago'
import type { IconProps } from '@wings-software/uicore/dist/icons/Icon'
import defaultTo from 'lodash-es/defaultTo'
import { useStrings } from 'framework/strings'
import {
  useGetTestConnectionResult,
  ConnectorConnectivityDetails,
  ConnectorValidationResult,
  ConnectorResponse,
  ErrorDetail
} from 'services/cd-ng'
 
import { StepIndex, STEP } from '@connectors/common/VerifyOutOfClusterDelegate/VerifyOutOfClusterDelegate'
import type { StepDetails } from '@connectors/interfaces/ConnectorInterface'
import { ConnectorStatus } from '@connectors/constants'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import useTestConnectionErrorModal from '@connectors/common/useTestConnectionErrorModal/useTestConnectionErrorModal'
import { GetTestConnectionValidationTextByType } from '../../utils/ConnectorUtils'
 
import css from '../ConnectorsListView.module.scss'
 
export type ErrorMessage = ConnectorValidationResult & { useErrorHandler?: boolean }
 
export interface ConnectivityStatusProps {
  data: ConnectorResponse
}
 
interface WarningTooltipProps {
  errorSummary?: string
  errors?: ErrorDetail[]
  onClick: (event: MouseEvent<HTMLDivElement>) => void
  errorDeatailsText: string
  noDetailsText: string
}
 
const WarningTooltip: React.FC<WarningTooltipProps> = ({
  errorSummary,
  errors,
  onClick,
  errorDeatailsText,
  noDetailsText
}) => {
  if (errorSummary) {
    return (
      <Layout.Vertical font={{ size: 'small' }} spacing="small" padding="small">
        <Text font={{ size: 'small' }} color={Color.WHITE}>
          {errorSummary}
        </Text>
        {errors ? (
          <Text color={Color.BLUE_400} onClick={onClick} className={css.viewDetails}>
            {errorDeatailsText}
          </Text>
        ) : null}
      </Layout.Vertical>
    )
  }
  return (
    <Text padding="small" color={Color.WHITE}>
      {noDetailsText}
    </Text>
  )
}
 
const renderReactTimeAgo = (
  connectorStatus?: string,
  lastTestedAt?: number,
  testedAt?: number
): ReactElement | undefined => {
  if (connectorStatus) {
    return (
      <Text font={{ size: 'small' }} color={Color.GREY_400}>
        {<ReactTimeago date={lastTestedAt || testedAt || ''} />}
      </Text>
    )
  }
  return undefined
}
 
const shouldExecuteStepVerify = (stepDetails: StepDetails): boolean =>
  stepDetails.step === StepIndex.get(STEP.TEST_CONNECTION) && stepDetails.status === 'PROCESS'
 
const ConnectivityStatus: React.FC<ConnectivityStatusProps> = ({ data }) => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  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 { gitDetails = {}, connector: { identifier = '' } = {} } = data
  const { branch, repoIdentifier } = gitDetails
  const [stepDetails, setStepDetails] = useState<StepDetails>({
    step: 1,
    intent: Intent.WARNING,
    status: 'PROCESS' // Replace when enum is added in uikit
  })
 
  const { openErrorModal } = useTestConnectionErrorModal({})
 
  const { mutate: reloadTestConnection } = useGetTestConnectionResult({
    identifier: identifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier: orgIdentifier,
      projectIdentifier: projectIdentifier,
      branch,
      repoIdentifier
    },
    requestOptions: {
      headers: {
        'content-type': 'application/json'
      }
    }
  })
 
  const executeStepVerify = async (): Promise<void> => {
    Eif (shouldExecuteStepVerify(stepDetails)) {
      try {
        const result = await reloadTestConnection()
        setStatus(result?.data?.status)
        setLastTestedAt(new Date().getTime())
        Eif (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)
      }
    }
  }
  const stepName = GetTestConnectionValidationTextByType(data.connector?.type)
 
  const renderStatusText = (
    icon: IconName,
    iconProps: Partial<IconProps>,
    tooltip: JSX.Element | string,
    statusText: string
  ): React.ReactElement => {
    return (
      <Text
        inline
        icon={icon}
        iconProps={iconProps}
        tooltip={tooltip}
        tooltipProps={{ isDark: true, position: 'bottom', popoverClassName: css.tooltip }}
      >
        {statusText}
      </Text>
    )
  }
 
  const connectorStatus = defaultTo(status, data.status?.status)
  const isStatusSuccess = connectorStatus === ConnectorStatus.SUCCESS
  const errorSummary = defaultTo(errorMessage?.errorSummary, data?.status?.errorSummary)
 
  const renderTooltip = () => {
    return (
      <WarningTooltip
        errorSummary={errorSummary}
        errors={defaultTo(errorMessage?.errors, data?.status?.errors)}
        onClick={e => {
          e.stopPropagation()
          openErrorModal((errorMessage as ErrorMessage) || data?.status)
        }}
        errorDeatailsText={getString('connectors.testConnectionStep.errorDetails')}
        noDetailsText={getString('noDetails')}
      />
    )
  }
 
  const renderStatus = () => {
    if (!(connectorStatus || errorMessage)) {
      return undefined
    }
    const statusMessageMap = {
      [`${ConnectorStatus.SUCCESS}`]: getString('success'),
      [`${ConnectorStatus.FAILURE}`]: getString('failed')
    }
 
    const statusMsg = defaultTo(statusMessageMap[`${connectorStatus}`], getString('na'))
    if (isStatusSuccess) {
      return renderStatusText('full-circle', { size: 6, color: Color.GREEN_500 }, '', statusMsg)
    }
 
    return renderStatusText('warning-sign', { size: 12, color: Color.RED_500 }, renderTooltip(), statusMsg)
  }
 
  if (testing) {
    return (
      <Layout.Horizontal>
        <Popover interactionKind={PopoverInteractionKind.HOVER} position={Position.LEFT_TOP}>
          <Button intent="primary" minimal loading />
          <div className={css.testConnectionPop}>
            <StepsProgress
              steps={[stepName]}
              intent={stepDetails.intent}
              current={stepDetails.step}
              currentStatus={stepDetails.status}
            />
          </div>
        </Popover>
        <Text style={{ margin: 8 }}>{getString('connectors.testInProgress')}</Text>
      </Layout.Horizontal>
    )
  }
 
  return (
    <Layout.Horizontal>
      <Layout.Vertical width="100px">
        <Layout.Horizontal spacing="small">{renderStatus()}</Layout.Horizontal>
        {renderReactTimeAgo(connectorStatus, lastTestedAt, data.status?.testedAt)}
      </Layout.Vertical>
      {!isStatusSuccess ? (
        <Button
          variation={ButtonVariation.SECONDARY}
          size={ButtonSize.SMALL}
          text={getString('test')}
          className={css.testBtn}
          onClick={e => {
            e.stopPropagation()
            setTesting(true)
            executeStepVerify()
            setStepDetails({
              step: 1,
              intent: Intent.WARNING,
              status: 'PROCESS' // Replace when enum is added in uikit
            })
          }}
          withoutBoxShadow
        />
      ) : undefined}
    </Layout.Horizontal>
  )
}
 
export default ConnectivityStatus