All files / modules/35-connectors/components/CreateConnector/commonSteps/DelegateSelectorStep DelegateSelectorStep.tsx

95.31% Statements 61/64
74.05% Branches 117/158
100% Functions 7/7
95.31% Lines 61/64

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              250x 250x 250x                     250x 250x 250x 250x               250x 250x         250x 250x 250x                                             250x 148x 148x 148x 50x     98x       98x 98x                                   206x 18x   188x 188x     188x     250x 468x                   250x 224x         206x 206x 206x 206x 206x 206x   206x 5x 5x         5x     5x 5x       206x   206x 206x 206x         206x 206x   206x                 206x       206x   206x                                                                     28x 28x         28x 3x 3x     25x           25x   25x                                               1x                                           250x  
/*
 * 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 { useParams } from 'react-router-dom'
import {
  Layout,
  Button,
  Formik,
  Text,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  FormikForm as Form,
  StepProps,
  ButtonVariation
} from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { DelegateTypes } from '@connectors/pages/connectors/utils/ConnectorUtils'
import type {
  ConnectorConfigDTO,
  ConnectorRequestBody,
  ConnectorInfoDTO,
  EntityGitDetails,
  ResponseConnectorResponse
} from 'services/cd-ng'
import { PageSpinner } from '@common/components'
import {
  DelegateOptions,
  DelegateSelector,
  DelegatesFoundState
} from '@connectors/components/CreateConnector/commonSteps/DelegateSelectorStep/DelegateSelector/DelegateSelector'
import { CredTypeValues, HashiCorpVaultAccessTypes } from '@connectors/interfaces/ConnectorInterface'
import useCreateEditConnector, { BuildPayloadProps } from '@connectors/hooks/useCreateEditConnector'
import css from '@connectors/components/CreateConnector/commonSteps/DelegateSelectorStep/DelegateSelector/DelegateSelector.module.scss'
 
interface DelegateSelectorStepData extends BuildPayloadProps {
  delegateSelectors: Array<string>
}
 
export interface DelegateSelectorProps {
  buildPayload: (data: DelegateSelectorStepData) => ConnectorRequestBody
  hideModal?: () => void
  onConnectorCreated?: (data?: ConnectorRequestBody) => void | Promise<void>
  isEditMode: boolean
  setIsEditMode?: (val: boolean) => void
  connectorInfo: ConnectorInfoDTO | void
  gitDetails?: EntityGitDetails
  disableGitSync?: boolean
  submitOnNextStep?: boolean
  customHandleCreate?: (payload: ConnectorConfigDTO) => Promise<ConnectorInfoDTO | undefined>
  customHandleUpdate?: (payload: ConnectorConfigDTO) => Promise<ConnectorInfoDTO | undefined>
}
 
type InitialFormData = { delegateSelectors: Array<string> }
 
const NoMatchingDelegateWarning: React.FC<{ delegatesFound: DelegatesFoundState; delegateSelectors: string[] }> =
  props => {
    const { getString } = useStrings()
    const { delegatesFound, delegateSelectors } = props
    if (delegatesFound === DelegatesFoundState.ActivelyConnected) {
      return <></>
    }
    const message =
      delegatesFound === DelegatesFoundState.NotConnected
        ? getString('connectors.delegate.noMatchingDelegatesActive')
        : getString('connectors.delegate.noMatchingDelegate', { tags: delegateSelectors.join(', ') })
    const dataName =
      delegatesFound === DelegatesFoundState.NotConnected ? 'delegateNoActiveMatchWarning' : 'delegateNoMatchWarning'
    return (
      <Text
        icon="warning-sign"
        iconProps={{ margin: { right: 'xsmall' }, color: Color.YELLOW_900 }}
        font={{ size: 'small', weight: 'semi-bold' }}
        data-name={dataName}
        className={css.noDelegateWarning}
      >
        {message}
      </Text>
    )
  }
 
function getInitialDelegateSelectors(
  isEditMode: boolean,
  connectorInfo: ConnectorInfoDTO | void,
  prevStepData: ConnectorConfigDTO | undefined
) {
  if (!isEditMode) {
    return []
  }
  let delegate = (connectorInfo as ConnectorInfoDTO & InitialFormData)?.spec?.delegateSelectors || []
  Iif (prevStepData?.delegateSelectors) {
    delegate = prevStepData.delegateSelectors
  }
  return delegate
}
 
const isDelegateSelectorMandatory = (prevStepData: ConnectorConfigDTO = {}): boolean => {
  return (
    DelegateTypes.DELEGATE_IN_CLUSTER === prevStepData?.delegateType ||
    DelegateTypes.DELEGATE_IN_CLUSTER_IRSA === prevStepData?.delegateType ||
    CredTypeValues.AssumeIAMRole === prevStepData?.credType ||
    CredTypeValues.AssumeRoleSTS === prevStepData?.credType ||
    HashiCorpVaultAccessTypes.VAULT_AGENT === prevStepData?.accessType ||
    HashiCorpVaultAccessTypes.K8s_AUTH === prevStepData?.accessType
  )
}
 
const DelegateSelectorStep: React.FC<StepProps<ConnectorConfigDTO> & DelegateSelectorProps> = props => {
  const { prevStepData, nextStep, buildPayload, customHandleCreate, customHandleUpdate, connectorInfo } = props
  const {
    accountId,
    projectIdentifier: projectIdentifierFromUrl,
    orgIdentifier: orgIdentifierFromUrl
  } = useParams<any>()
  const projectIdentifier = connectorInfo ? connectorInfo.projectIdentifier : projectIdentifierFromUrl
  const orgIdentifier = connectorInfo ? connectorInfo.orgIdentifier : orgIdentifierFromUrl
  const { getString } = useStrings()
  const isGitSyncEnabled = useAppStore().isGitSyncEnabled && !props.disableGitSync && orgIdentifier && projectIdentifier
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
 
  const afterSuccessHandler = (response: ResponseConnectorResponse): void => {
    props.onConnectorCreated?.(response?.data)
    Iif (prevStepData?.branch) {
      // updating connector branch to handle if new branch was created while commit
      prevStepData.branch = response?.data?.gitDetails?.branch
    }
 
    Iif (stepDataRef?.skipDefaultValidation) {
      props.hideModal?.()
    } else {
      nextStep?.({ ...prevStepData, ...stepDataRef } as ConnectorConfigDTO)
      props.setIsEditMode?.(true)
    }
  }
 
  const initialDelegateSelectors = getInitialDelegateSelectors(props.isEditMode, props.connectorInfo, prevStepData)
 
  const initialValues = { delegateSelectors: initialDelegateSelectors }
  const [delegateSelectors, setDelegateSelectors] = useState<Array<string>>(initialDelegateSelectors)
  const [mode, setMode] = useState<DelegateOptions>(
    delegateSelectors.length || isDelegateSelectorMandatory(prevStepData)
      ? DelegateOptions.DelegateOptionsSelective
      : DelegateOptions.DelegateOptionsAny
  )
  const [delegatesFound, setDelegatesFound] = useState<DelegatesFoundState>(DelegatesFoundState.ActivelyConnected)
  let stepDataRef: ConnectorConfigDTO | null = null
 
  const { onInitiate, loading } = useCreateEditConnector<DelegateSelectorStepData>({
    accountId,
    isEditMode: props.isEditMode,
    isGitSyncEnabled,
    afterSuccessHandler,
    gitDetails: props.gitDetails
  })
 
  const isSaveButtonDisabled =
    (isDelegateSelectorMandatory(prevStepData) && delegateSelectors.length === 0) ||
    (mode === DelegateOptions.DelegateOptionsSelective && delegateSelectors.length === 0) ||
    loading
 
  const connectorName = (prevStepData as ConnectorConfigDTO)?.name || (connectorInfo as ConnectorInfoDTO)?.name
 
  return (
    <>
      {!isGitSyncEnabled && loading ? (
        <PageSpinner
          message={
            props.isEditMode
              ? getString('connectors.updating', { name: connectorName })
              : getString('connectors.creating', { name: connectorName })
          }
        />
      ) : null}
      <Layout.Vertical height={'inherit'} padding={{ left: 'small' }}>
        <Text
          font={{ variation: FontVariation.H3 }}
          margin={{ top: 'small' }}
          color={Color.BLACK}
          id="delegateSelectorStepTitle"
        >
          {getString('delegate.DelegateselectionLabel')}
        </Text>
        <ModalErrorHandler bind={setModalErrorHandler} />
        <Formik
          initialValues={{
            ...initialValues,
            ...prevStepData
          }}
          formName="delegateSelectorStepForm"
          //   Enable when delegateSelector adds form validation
          // validationSchema={Yup.object().shape({
          //   delegateSelector: Yup.string().when('delegateType', {
          //     is: DelegateTypes.DELEGATE_IN_CLUSTER,
          //     then: Yup.string().trim().required(i18n.STEP.TWO.validation.delegateSelector)
          //   })
          // })}
          onSubmit={stepData => {
            modalErrorHandler?.hide()
            const updatedStepData = {
              ...stepData,
              delegateSelectors: mode === DelegateOptions.DelegateOptionsAny ? [] : delegateSelectors
            }
 
            if (props.submitOnNextStep) {
              nextStep?.({ ...prevStepData, ...updatedStepData, projectIdentifier, orgIdentifier })
              return
            }
 
            const connectorData: DelegateSelectorStepData = {
              ...prevStepData,
              ...updatedStepData,
              projectIdentifier: projectIdentifier,
              orgIdentifier: orgIdentifier
            }
            stepDataRef = updatedStepData
 
            onInitiate({
              connectorFormData: connectorData,
              buildPayload,
              customHandleCreate,
              customHandleUpdate
            })
          }}
        >
          <Form>
            <DelegateSelector
              mode={mode}
              setMode={setMode}
              delegateSelectors={delegateSelectors}
              setDelegateSelectors={setDelegateSelectors}
              setDelegatesFound={setDelegatesFound}
              delegateSelectorMandatory={isDelegateSelectorMandatory(prevStepData)}
              accountId={accountId}
              orgIdentifier={orgIdentifier}
              projectIdentifier={projectIdentifier}
            />
            <Layout.Horizontal padding={{ top: 'small' }} margin={{ top: 'xxxlarge' }} spacing="medium">
              <Button
                text={getString('back')}
                icon="chevron-left"
                onClick={() => props?.previousStep?.(props?.prevStepData)}
                data-name="awsBackButton"
                variation={ButtonVariation.SECONDARY}
              />
              <Button
                type="submit"
                intent={'primary'}
                text={getString(props.submitOnNextStep ? 'continue' : 'saveAndContinue')}
                className={css.saveAndContinue}
                disabled={isSaveButtonDisabled}
                rightIcon="chevron-right"
                data-testid="delegateSaveAndContinue"
              />
              <NoMatchingDelegateWarning delegatesFound={delegatesFound} delegateSelectors={delegateSelectors} />
            </Layout.Horizontal>
          </Form>
        </Formik>
      </Layout.Vertical>
    </>
  )
}
 
export default DelegateSelectorStep