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

91.53% Statements 54/59
62.3% Branches 38/61
100% Functions 5/5
91.53% Lines 54/59

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              250x 250x                       250x 250x 250x 250x 250x             250x 250x 250x 250x 250x 250x 250x 250x 250x                                           250x 256x         256x 256x 256x 256x 256x 256x   256x 256x 256x 256x 256x   256x 62x 62x   36x 36x 36x   26x 26x 26x                 26x   26x       26x 26x 26x                             256x 256x 106x 150x 2x   148x                 256x               62x                         437x       437x                                                                                 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, { useRef, useState } from 'react'
import {
  Layout,
  Button,
  Formik,
  StepProps,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  FormikForm,
  Container,
  Text,
  ButtonVariation
} from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
import { pick } from 'lodash-es'
import {
  ConnectorConfigDTO,
  ConnectorInfoDTO,
  ResponseBoolean,
  validateTheIdentifierIsUniquePromise,
  Failure
} from 'services/cd-ng'
import { String, useStrings } from 'framework/strings'
import { NameIdDescriptionTags } from '@common/components'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import GitContextForm, { GitContextProps, IGitContextFormProps } from '@common/components/GitContextForm/GitContextForm'
import { saveCurrentStepData } from '@connectors/pages/connectors/utils/ConnectorUtils'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { getHeadingIdByType } from '../../../pages/connectors/utils/ConnectorHelper'
import css from './ConnectorDetailsStep.module.scss'
 
export type DetailsForm = Pick<ConnectorInfoDTO, 'name' | 'identifier' | 'description' | 'tags'> & GitContextProps
 
interface ConnectorDetailsStepProps extends StepProps<ConnectorInfoDTO> {
  type: ConnectorInfoDTO['type']
  name: string
  setFormData?: (formData: ConnectorConfigDTO) => void
  formData?: ConnectorConfigDTO
  isEditMode?: boolean
  connectorInfo?: ConnectorInfoDTO | void
  gitDetails?: IGitContextFormProps
  mock?: ResponseBoolean
  disableGitSync?: boolean
}
 
type Params = {
  accountId: string
  projectIdentifier: string
  orgIdentifier: string
}
 
const ConnectorDetailsStep: React.FC<StepProps<ConnectorConfigDTO> & ConnectorDetailsStepProps> = props => {
  const { prevStepData, nextStep, disableGitSync, connectorInfo } = props
  const {
    accountId,
    projectIdentifier: projectIdentifierFromUrl,
    orgIdentifier: orgIdentifierFromUrl
  } = useParams<Params>()
  const projectIdentifier = connectorInfo ? connectorInfo.projectIdentifier : projectIdentifierFromUrl
  const orgIdentifier = connectorInfo ? connectorInfo.orgIdentifier : orgIdentifierFromUrl
  const { isGitSyncEnabled: gitSyncAppStoreEnabled } = useAppStore()
  const isGitSyncEnabled = gitSyncAppStoreEnabled && !disableGitSync
  const showGitContextForm = isGitSyncEnabled && orgIdentifier && projectIdentifier
 
  const mounted = useRef(false)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const [loading, setLoading] = useState(false)
  const isEdit = props.isEditMode || prevStepData?.isEdit
  const { getString } = useStrings()
 
  const handleSubmit = async (formData: ConnectorConfigDTO): Promise<void> => {
    mounted.current = true
    if (isEdit) {
      //In edit mode validateTheIdentifierIsUnique API not required
      props.setFormData?.(formData)
      nextStep?.({ ...props.connectorInfo, ...prevStepData, ...formData })
      return
    }
    setLoading(true)
    try {
      const response = await validateTheIdentifierIsUniquePromise({
        queryParams: {
          identifier: formData.identifier,
          accountIdentifier: accountId,
          orgIdentifier: orgIdentifier,
          projectIdentifier: projectIdentifier
        },
        mock: props.mock
      })
      setLoading(false)
 
      Iif ('SUCCESS' !== response.status) {
        modalErrorHandler?.showDanger((response as Failure)?.message || '')
        return
      }
      Eif (response.data) {
        props.setFormData?.(formData)
        nextStep?.({ ...props.connectorInfo, ...prevStepData, ...formData })
      } else {
        modalErrorHandler?.showDanger(
          getString('validation.duplicateIdError', {
            connectorName: formData.name,
            connectorIdentifier: formData.identifier
          })
        )
      }
    } catch (error) {
      setLoading(false)
      modalErrorHandler?.showDanger(error.message)
    }
  }
 
  const getInitialValues = () => {
    if (isEdit) {
      return { ...pick(props.connectorInfo, ['name', 'identifier', 'description', 'tags']) }
    } else if (prevStepData) {
      return { ...pick(prevStepData, ['name', 'identifier', 'description', 'tags']) }
    } else {
      return {
        name: '',
        description: '',
        identifier: '',
        tags: {}
      }
    }
  }
 
  return (
    <Layout.Vertical spacing="xxlarge" className={css.firstep}>
      <Text font={{ variation: FontVariation.H3 }}>{getString(getHeadingIdByType(props.type))}</Text>
      <ModalErrorHandler bind={setModalErrorHandler} style={{ maxWidth: '740px' }} />
 
      <Container className={css.connectorForm}>
        <Formik<DetailsForm>
          onSubmit={formData => {
            handleSubmit(formData)
          }}
          formName={`connectorDetailsStepForm${props.type}`}
          validationSchema={Yup.object().shape({
            name: NameSchema(),
            identifier: IdentifierSchema()
          })}
          initialValues={{
            ...(getInitialValues() as DetailsForm),
            ...props.formData
          }}
        >
          {formikProps => {
            saveCurrentStepData<ConnectorInfoDTO>(
              props.getCurrentStepData,
              formikProps.values as unknown as ConnectorInfoDTO
            )
            return (
              <FormikForm>
                <Container style={{ minHeight: 460 }}>
                  <NameIdDescriptionTags
                    className={css.formElm}
                    formikProps={formikProps}
                    identifierProps={{ inputName: 'name', isIdentifierEditable: !isEdit }}
                  />
 
                  {showGitContextForm ? (
                    <GitSyncStoreProvider>
                      <GitContextForm
                        formikProps={formikProps}
                        gitDetails={props.gitDetails}
                        className={'gitDetailsContainer'}
                      />
                    </GitSyncStoreProvider>
                  ) : (
                    <></>
                  )}
                </Container>
                <Layout.Horizontal>
                  <Button
                    type="submit"
                    intent="primary"
                    rightIcon="chevron-right"
                    disabled={loading}
                    variation={ButtonVariation.PRIMARY}
                  >
                    <String stringID="continue" />
                  </Button>
                </Layout.Horizontal>
              </FormikForm>
            )
          }}
        </Formik>
      </Container>
    </Layout.Vertical>
  )
}
 
export default ConnectorDetailsStep