All files / modules/35-connectors/components/CreateConnector/CEK8sConnector OverviewStep.tsx

89.47% Statements 68/76
57.27% Branches 63/110
100% Functions 12/12
89.19% Lines 66/74

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              219x 219x 219x 219x 219x 219x                         219x 219x 219x 219x 219x 219x               219x 219x   219x 219x                                       219x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x   9x 2x                 9x       9x 2x 2x 2x   2x       2x             9x 2x 2x 2x     9x 1x 1x 1x         1x         1x 1x 1x                 1x   1x 1x 1x 1x                                     9x 9x           9x                   9x                 1x         16x                               18x                   1x 1x 1x 1x                                                                                   219x  
/*
 * 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, { useEffect, useMemo, useRef, useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import * as Yup from 'yup'
import { pick, omit as _omit, defaultTo as _defaultTo } from 'lodash-es'
import cx from 'classnames'
import {
  Button,
  ButtonVariation,
  Container,
  Formik,
  FormikForm,
  FormInput,
  Layout,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  SelectOption,
  StepProps
} from '@wings-software/uicore'
import { NameIdDescriptionTags } from '@common/components'
import { StringUtils, useToaster } from '@common/exports'
import { getHeadingIdByType } from '@connectors/pages/connectors/utils/ConnectorHelper'
import routes from '@common/RouteDefinitions'
import { String, useStrings } from 'framework/strings'
import {
  ConnectorConfigDTO,
  ConnectorInfoDTO,
  Failure,
  ResponseBoolean,
  useGetConnectorListV2,
  validateTheIdentifierIsUniquePromise
} from 'services/cd-ng'
import { CE_K8S_CONNECTOR_CREATION_EVENTS } from '@connectors/trackingConstants'
import { useStepLoadTelemetry } from '@connectors/common/useTrackStepLoad/useStepLoadTelemetry'
import type { DetailsForm } from '../commonSteps/ConnectorDetailsStep'
import css from '../commonSteps/ConnectorDetailsStep.module.scss'
import overviewCss from './CEK8sConnector.module.scss'
 
interface OverviewStepProps {
  type: ConnectorInfoDTO['type']
  name: string
  setFormData?: (formData: ConnectorConfigDTO) => void
  formData?: ConnectorConfigDTO
  isEditMode?: boolean
  connectorInfo?: ConnectorInfoDTO | void
  mock?: ResponseBoolean
}
 
type Params = {
  accountId: string
  projectIdentifier: string
  orgIdentifier: string
}
 
type OverviewDetailsForm = DetailsForm & { referenceConnector: string }
 
const OverviewStep: React.FC<StepProps<ConnectorConfigDTO> & OverviewStepProps> = props => {
  const { prevStepData, nextStep } = props
  const { accountId, projectIdentifier, orgIdentifier } = useParams<Params>()
  const mounted = useRef(false)
  const { showError } = useToaster()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const [loading, setLoading] = useState(false)
  const [selectedConnector, setSelectedConnector] = useState<SelectOption>()
  const [connectorOptions, setConnectorOptions] = useState<SelectOption[]>([])
  const isEdit = props.isEditMode || prevStepData?.isEdit
  const { getString } = useStrings()
 
  useStepLoadTelemetry(CE_K8S_CONNECTOR_CREATION_EVENTS.LOAD_OVERVIEW_STEP)
 
  const defaultQueryParams = useMemo(
    () => ({
      accountIdentifier: accountId,
      searchTerm: '',
      pageIndex: 0,
      pageSize: 100
    }),
    [accountId]
  )
 
  const { mutate: fetchConnectors, loading: connectorsLoading } = useGetConnectorListV2({
    queryParams: defaultQueryParams
  })
 
  const fetchAndSetConnectors = async () => {
    Eif (document.visibilityState === 'visible') {
      try {
        const connectorData = await fetchConnectors({ filterType: 'Connector', types: ['K8sCluster'] })
        const options: SelectOption[] =
          connectorData?.data?.content?.map(dataContent => ({
            value: _defaultTo(dataContent.connector?.identifier, ''),
            label: _defaultTo(dataContent.connector?.name, '')
          })) || []
        setConnectorOptions(options)
      } catch (e) {
        showError(e.message)
      }
    }
  }
 
  useEffect(() => {
    fetchAndSetConnectors()
    window.addEventListener('visibilitychange', fetchAndSetConnectors)
    return () => window.removeEventListener('visibilitychange', fetchAndSetConnectors)
  }, [])
 
  const handleSubmit = async (formData: ConnectorConfigDTO): Promise<void> => {
    mounted.current = true
    const configInfo = { ...props.connectorInfo } as ConnectorConfigDTO
    const spec = {
      featuresEnabled: configInfo?.spec?.featuresEnabled || ['VISIBILITY'],
      connectorRef: selectedConnector?.value || formData.referenceConnector,
      fixFeatureSelection: configInfo?.spec?.featuresEnabled?.includes('OPTIMIZATION') // TEMPORARY FLAG TO FIX FEATURE SELECTION IN CASE OF K8s RULE CREATION FLOW
    }
    Iif (isEdit) {
      //In edit mode validateTheIdentifierIsUnique API not required
      props.setFormData?.(formData)
      nextStep?.(_omit({ ...props.connectorInfo, ...prevStepData, ...formData }, 'referenceConnector'))
    } else {
      setLoading(true)
      try {
        const response = await validateTheIdentifierIsUniquePromise({
          queryParams: {
            identifier: formData.identifier,
            accountIdentifier: accountId,
            orgIdentifier: orgIdentifier,
            projectIdentifier: projectIdentifier
          },
          mock: props.mock
        })
        setLoading(false)
 
        Eif ('SUCCESS' === response.status) {
          Eif (response.data) {
            props.setFormData?.(formData)
            nextStep?.(_omit({ ...props.connectorInfo, ...prevStepData, ...formData, spec }, 'referenceConnector'))
          } else {
            modalErrorHandler?.showDanger(
              getString('validation.duplicateIdError', {
                connectorName: formData.name,
                connectorIdentifier: formData.identifier
              })
            )
          }
        } else {
          throw response as Failure
        }
      } catch (error) {
        setLoading(false)
        modalErrorHandler?.showDanger(error.message)
      }
    }
  }
 
  const getInitialValues = () => {
    Iif (isEdit) {
      return {
        ...pick(props.connectorInfo, ['name', 'identifier', 'description', 'tags']),
        referenceConnector: (props.connectorInfo as ConnectorInfoDTO)?.spec?.connectorRef
      }
    } else {
      return {
        name: '',
        description: '',
        identifier: '',
        tags: {},
        referenceConnector: props.prevStepData?.spec?.connectorRef
      }
    }
  }
 
  return (
    <Layout.Vertical spacing="xxlarge" className={cx(css.firstep, overviewCss.overviewStep)}>
      <div className={css.heading}>{getString(getHeadingIdByType(props.type))}</div>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <div className={overviewCss.infoSection}>{getString('connectors.ceK8.infoText')}</div>
      <Container padding="small" className={cx(css.connectorForm, overviewCss.formCont)}>
        <Formik<OverviewDetailsForm>
          formName="overViewStepForm"
          onSubmit={formData => {
            handleSubmit(formData)
          }}
          validationSchema={Yup.object().shape({
            name: Yup.string().trim().required(getString('validation.connectorName')),
            identifier: Yup.string().when('name', {
              is: val => val?.length,
              then: Yup.string()
                .trim()
                .required(getString('validation.identifierRequired'))
                .matches(/^(?![0-9])[0-9a-zA-Z_$]*$/, getString('validation.validIdRegex'))
                .notOneOf(StringUtils.illegalIdentifiers)
            }),
            referenceConnector: Yup.string().required('Select a connector')
          })}
          initialValues={{
            ...(getInitialValues() as OverviewDetailsForm),
            ...prevStepData,
            ...props.formData
          }}
        >
          {formikProps => {
            return (
              <FormikForm>
                <Container style={{ minHeight: 300 }}>
                  <Layout.Horizontal flex={{ justifyContent: 'start' }}>
                    <FormInput.Select
                      name="referenceConnector"
                      label={getString('connectors.ceK8.selectConnectorLabel')}
                      items={connectorOptions}
                      disabled={connectorsLoading}
                      onChange={_item => {
                        const val = `${_item.label}-Cost-access`
                        setSelectedConnector(_item)
                        formikProps.setFieldValue('name', val)
                        formikProps.setFieldValue(
                          'identifier',
                          val
                            .trim()
                            .replace(/[^0-9a-zA-Z_$ ]/g, '')
                            .replace(/ +/g, '_')
                        )
                      }}
                      className={overviewCss.selectConnector}
                    />
                    <Link
                      to={routes.toConnectors({ accountId })}
                      target="_blank"
                      className={overviewCss.createNewConnCta}
                    >
                      <Button
                        variation={ButtonVariation.SECONDARY}
                        text={getString('connectors.ceK8.overview.createNewConnectorCta')}
                        icon={'plus'}
                      />
                    </Link>
                  </Layout.Horizontal>
                  <NameIdDescriptionTags
                    className={cx(css.formElm, overviewCss.nameField)}
                    formikProps={formikProps}
                    identifierProps={{ inputName: 'name', isIdentifierEditable: !isEdit }}
                  />
                </Container>
                <Layout.Horizontal>
                  <Button type="submit" intent="primary" rightIcon="chevron-right" disabled={loading}>
                    <String stringID="saveAndContinue" />
                  </Button>
                </Layout.Horizontal>
              </FormikForm>
            )
          }}
        </Formik>
      </Container>
    </Layout.Vertical>
  )
}
 
export default OverviewStep