All files / modules/35-connectors/components/CreateConnector/AppDynamicsConnector CreateAppDynamicsConnector.tsx

88.1% Statements 37/42
69.23% Branches 36/52
77.78% Functions 7/9
88.1% Lines 37/42

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              219x 219x 219x 219x 219x 219x 219x     219x 219x       219x 219x 219x 219x                               46x 46x 46x 5x               46x                 46x                   4x                                 5x 5x 5x 5x 4x     5x   5x 4x 1x 1x     5x                                                                               46x                                   4x 3x           1x 1x                                         219x          
/*
 * 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, { useMemo } from 'react'
import { Color } from '@harness/design-system'
import { Layout, Button, Text, FormInput, FormikForm, Container } from '@wings-software/uicore'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { useStrings } from 'framework/strings'
import { AppDynamicsAuthType, buildAppDynamicsPayload } from '@connectors/pages/connectors/utils/ConnectorUtils'
import type { ConnectorConfigDTO } from 'services/cd-ng'
import type { ConnectionConfigProps } from '../CommonCVConnector/constants'
import { cvConnectorHOC } from '../CommonCVConnector/CVConnectorHOC'
import {
  ConnectorSecretField,
  ConnectorSecretFieldProps
} from '../CommonCVConnector/components/ConnectorSecretField/ConnectorSecretField'
import { initializeAppDConnector } from './utils'
import { StepDetailsHeader } from '../CommonCVConnector/components/CredentialsStepHeader/CredentialsStepHeader'
import commonStyles from '@connectors/components/CreateConnector/commonSteps/ConnectorCommonStyles.module.scss'
import styles from './CreateAppDynamicsConnector.module.scss'
 
interface UsernamePasswordAndApiClientOptionProps extends Omit<ConnectorSecretFieldProps, 'secretInputProps'> {
  onAuthTypeChange: (authType: string) => void
  authTypeValue?: string
}
 
function UsernamePasswordAndApiClientOption(props: UsernamePasswordAndApiClientOptionProps): JSX.Element {
  const {
    onAuthTypeChange,
    authTypeValue,
    accountIdentifier,
    projectIdentifier,
    orgIdentifier,
    onSuccessfulFetch,
    secretFieldValue
  } = props
  const { getString } = useStrings()
  const authOptions = useMemo(
    () => [
      { label: getString('usernamePassword'), value: AppDynamicsAuthType.USERNAME_PASSWORD },
      { label: getString('connectors.appD.apiClient'), value: AppDynamicsAuthType.API_CLIENT_TOKEN }
    ],
    []
  )
 
  const fieldProps =
    authTypeValue === AppDynamicsAuthType.API_CLIENT_TOKEN
      ? [
          { name: 'clientId', label: getString('connectors.appD.clientId'), key: 'clientId' },
          { name: 'clientSecretRef', label: getString('common.clientSecret'), key: 'clientSecretRef' }
        ]
      : [
          { name: 'username', label: getString('username'), key: 'username' },
          { name: 'password', label: getString('password'), key: 'password' }
        ]
  return (
    <Container>
      <Container flex style={{ alignItems: 'baseline' }}>
        <Text color={Color.BLACK} font={{ weight: 'bold' }}>
          {getString('authentication')}
        </Text>
        <FormInput.Select
          name="authType"
          items={authOptions}
          className={commonStyles.authTypeSelect}
          onChange={updatedAuth => onAuthTypeChange(updatedAuth.value as string)}
        />
      </Container>
      <FormInput.Text {...fieldProps[0]} />
      <ConnectorSecretField
        secretInputProps={fieldProps[1]}
        accountIdentifier={accountIdentifier}
        projectIdentifier={projectIdentifier}
        orgIdentifier={orgIdentifier}
        secretFieldValue={secretFieldValue}
        onSuccessfulFetch={onSuccessfulFetch}
      />
    </Container>
  )
}
 
function AppDynamicsConfigStep(props: ConnectionConfigProps): JSX.Element {
  const { getString } = useStrings()
  const { nextStep, prevStepData, connectorInfo, accountId, projectIdentifier, orgIdentifier } = props
  const initialValues = initializeAppDConnector({ prevStepData, projectIdentifier, accountId, orgIdentifier })
  const handleSubmit = (formData: ConnectorConfigDTO) => {
    nextStep?.({ ...connectorInfo, ...prevStepData, ...formData })
  }
 
  const { spec, ...prevData } = props.prevStepData || {}
  let secretFieldValue: any
  if (initialValues.authType === AppDynamicsAuthType.USERNAME_PASSWORD) {
    secretFieldValue = prevData?.password?.referenceString || spec?.passwordRef
  } else Eif (initialValues.authType === AppDynamicsAuthType.API_CLIENT_TOKEN) {
    secretFieldValue = prevData?.clientSecretRef?.referenceString || spec?.clientSecretRef
  }
 
  return (
    <>
      <StepDetailsHeader connectorTypeLabel={getString('connectors.appdLabel')} />
      <Formik
        enableReinitialize
        initialValues={{
          ...initialValues
        }}
        validationSchema={Yup.object().shape({
          url: Yup.string().trim().required(getString('connectors.appD.validation.controllerURL')),
          accountName: Yup.string().trim().required(getString('validation.accountName')),
          authType: Yup.string().trim(),
          username: Yup.string()
            .nullable()
            .when('authType', {
              is: AppDynamicsAuthType.USERNAME_PASSWORD,
              then: Yup.string().required(getString('validation.username'))
            }),
          password: Yup.string()
            .nullable()
            .when('authType', {
              is: AppDynamicsAuthType.USERNAME_PASSWORD,
              then: Yup.string().required(getString('validation.password'))
            }),
          clientId: Yup.string()
            .nullable()
            .when('authType', {
              is: AppDynamicsAuthType.API_CLIENT_TOKEN,
              then: Yup.string().required(getString('connectors.appD.validation.clientId'))
            }),
          clientSecretRef: Yup.string()
            .nullable()
            .when('authType', {
              is: AppDynamicsAuthType.API_CLIENT_TOKEN,
              then: Yup.string().required(getString('connectors.appD.validation.clientSecret'))
            })
        })}
        onSubmit={handleSubmit}
      >
        {formikProps => (
          <FormikForm className={styles.connectionForm}>
            <Layout.Vertical spacing="large" className={styles.appDContainer}>
              <FormInput.Text label={getString('connectors.appD.controllerURL')} name="url" />
              <FormInput.Text label={getString('connectors.appD.accountName')} name="accountName" />
              <UsernamePasswordAndApiClientOption
                accountIdentifier={props.accountId}
                projectIdentifier={props.projectIdentifier}
                orgIdentifier={props.orgIdentifier}
                secretFieldValue={secretFieldValue}
                onSuccessfulFetch={result => {
                  if (initialValues.authType === AppDynamicsAuthType.API_CLIENT_TOKEN) {
                    formikProps.setFieldValue('clientSecretRef', result)
                  } else if (initialValues.authType === AppDynamicsAuthType.USERNAME_PASSWORD) {
                    formikProps.setFieldValue('password', result)
                  }
                }}
                authTypeValue={formikProps.values.authType}
                onAuthTypeChange={updatedAuth => {
                  if (updatedAuth === AppDynamicsAuthType.API_CLIENT_TOKEN) {
                    formikProps.setValues({
                      ...formikProps.values,
                      authType: updatedAuth,
                      username: null,
                      password: null
                    })
                  } else Eif (updatedAuth === AppDynamicsAuthType.USERNAME_PASSWORD) {
                    formikProps.setValues({
                      ...formikProps.values,
                      authType: updatedAuth,
                      clientId: null,
                      clientSecretRef: null
                    })
                  }
                }}
              />
            </Layout.Vertical>
            <Layout.Horizontal spacing="large">
              <Button onClick={() => props.previousStep?.({ ...props.prevStepData })} text={getString('back')} />
              <Button type="submit" intent="primary" text={getString('continue')} />
            </Layout.Horizontal>
          </FormikForm>
        )}
      </Formik>
    </>
  )
}
 
export default cvConnectorHOC({
  connectorType: 'AppDynamics',
  ConnectorCredentialsStep: AppDynamicsConfigStep,
  buildSubmissionPayload: buildAppDynamicsPayload
})